完整的項目視頻課程請識別下面的二維碼進入個人B站:typescript
本項目是基於鴻蒙的電子詞典,支持使用本地詞庫和遠程詞庫。本地詞庫使用SQLite數據庫、遠程詞典使用爬蟲獲取的單詞數據。爬蟲使用JSoup庫(基於Java語言)。欲知詳情,請繼續觀看本課程的視頻。
數據庫
本課程以實戰爲宗旨,step by step來完整在線電子詞典項目。例如,下面是異步搜索網絡詞庫的源代碼。微信
class AsyncSearchWord extends Thread { private String word; private RdbStore store; private SearchWordCallback callback; public AsyncSearchWord(String word, RdbStore store, SearchWordCallback callback) { this.word = word; this.store = store; this.callback = callback; }
public void run() { try { Document doc = Jsoup.connect("https://www.iciba.com/word?w=" + word).get(); Elements ulElements = doc.getElementsByClass("Mean_part__1RA2V"); String insertSQL = "insert into t_words(word,type,meanings) values(?,?,?);"; List<WordData> wordDataList = new ArrayList<>(); for(Element ulElement: ulElements) { Elements liElements = ulElement.getElementsByTag("li");
for(Element liElement:liElements) { WordData wordData = new WordData(); Elements iElements = liElement.getElementsByTag("i"); for(Element iElement:iElements) { wordData.type = iElement.text(); break; } Elements divElements = liElement.getElementsByTag("div"); // 獲得詞義 for(Element divElement:divElements) { wordData.meanings = divElements.text(); break; } // 插入每個詞性的解釋 wordDataList.add(wordData); store.executeSql(insertSQL,new String[]{word, wordData.type,wordData.meanings});
}
break; } if(callback != null) { callback.onResult(wordDataList); }
} catch (Exception e) {
} }}
從本地詞庫搜索單詞的源代碼:
網絡
public ArrayList<WordData> searchLocalDict(String word) { word = word.toLowerCase(); String[] args = new String[]{word}; ResultSet resultSet = store.querySql("select * from t_words where word = ?",args);
ArrayList<WordData> result = new ArrayList<>(); int i = 0; while(resultSet.goToNextRow()) { WordData wordData = new WordData(); wordData.type = resultSet.getString(2); wordData.meanings = resultSet.getString(3); result.add(wordData);
} resultSet.close(); return result;}
本文分享自微信公衆號 - 極客起源(geekculture)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。異步