fetch、promise、およびその他の js について学習するために、特定の日本語テキストから (難易度に基づいて) 学習する単語を提案する小さなスクリプトを作成しようとしています。
クロモジンと呼ばれる日本語のパーサーを利用します。
クロモジンのようなパーサーが行うことは、フレーズを単語にトークン化することです。
例:「日本語が上手ですね!」→ トークン化された単語: [{surface_form: 日本語}, {surface_form: が}, {surface_form: 上手}, {surface_form: です}, {surface_form: ね}, {surface_form: !}]
このスクリプトは、まずデータから単語をトークン化し、次に日本語辞書の API (jisho.org) を使用して、トークン化された各単語の対応する JLPT レベルを取得します。
app.js ファイル:
import { tokenize, getTokenizer} from "kuromojin";
import { parseIntoJisho} from "./parseintojisho.js";
const text = "日本語が上手ですね!";
let tokenSet = new Set();
getTokenizer().then(tokenizer => {});
tokenize(text).then(results => { // the result is an array of objects
results.forEach((token) => {
tokenSet.add(token.surface_form);
})
console.log("======Begin to find JLPT level for below items======");
tokenSet.forEach((item) => {
console.log(item);
parseIntoJisho(item); // will throw a console log of whichever item's corresponding data is resolved, regardless of item order here, right?
});
})
parseintojisho.js ファイル:
import fetch from 'node-fetch';
/* @param data is string */
export function parseIntoJisho(data) {
fetch(encodeURI(`https://jisho.org/api/v1/search/words?keyword=${data}`))
.then(res => res.json())
.then(jsondata => {
let JLPTvalueArray = jsondata.data[0].jlpt;
if (JLPTvalueArray.length) {
let jlptLevel = JLPTvalueArray.flatMap(str => str.match(/\d+/));
const max = Math.max(...jlptLevel);
if (max >= 3) {
console.log(data + " is of JLPT level N3 or above.")
} else console.log(data + " is of JLPT level N1 or N2.");
} else console.log(data + " has no JLPT value.")
})
.catch(function(err){
console.log("No data for " + data);
})
}
スクリプトは機能しますが、トークン化された各単語に対応する JLPT レベルが順番に表示されるのではなく、ランダムに表示されます。対応するデータが最初に解決された方がコンソール ログに表示されると思いますか?
私が見つけたのは、それPromise.All()
が私の問題を解決するかもしれないということですが、それを正しく実装する方法を見つけることができませんでした.
取得した JLPT レベルを、渡されたトークン化された項目の順序に並べる方法はありますparseIntoJisho(item);
か?
$ node app.js
======Begin to find JLPT level for below items======
日本語
が
上手
です
ね
!
です has no JLPT value. // should be "日本語 has no JLPT value." here instead
No data for ! // should be "が has no JLPT value." here instead
上手 is of JLPT level N3 or above.
日本語 has no JLPT value. // should be "です has no JLPT value." here instead
ね is of JLPT level N3 or above.
が has no JLPT value. // should be "No data for !" here instead