# APIエンドポイント @app.route('/extract', methods=['POST']) def extract(): data = request.get_json() if not data or 'title' not in data: return jsonify({"error": "title が指定されていません"}), 400
word_tokens = for t in tokens: if t.part_of_speech()[0] == "名詞": noun = normalize_noun(t.surface()) if is_valid_token(noun, "名詞"): word_tokens.append(noun)
normalized_forms = for t in tokens: pos_major = t.part_of_speech()[0] if pos_major in {"動詞", "形容詞"}: base = convert_base(t.normalized_form()) if base != t.surface() and is_valid_token(base, pos_major): normalized_forms.append(base)
def split_bunsetsu(tokens) -> list[list]: bunsetsu, current = , for t in tokens: if t.part_of_speech()[0] in {"名詞", "動詞", "形容詞", "形状詞"}: if current: bunsetsu.append(current) current = [t] else: current.append(t) if current: bunsetsu.append(current) return bunsetsu
bunsetsu_phrases = for seg in split_bunsetsu(tokens): phrase = ''.join(t.surface() for t in seg) if len(phrase) > 1 and is_valid(phrase): bunsetsu_phrases.append(phrase)
compound_phrases = for i in range(len(tokens) - 2): t1, t2, t3 = tokens[i], tokens[i+1], tokens[i+2] if (t1.part_of_speech()[0] == "名詞" and t2.surface() in {"の", "な"} and t3.part_of_speech()[0] == "名詞"): phrase = t1.surface() + t2.surface() + t3.surface() if is_valid(phrase): compound_phrases.append(phrase)
noun_bigrams = for i in range(len(word_tokens)): for j in range(i + 1, len(word_tokens)): for a, b in [(word_tokens[i], word_tokens[j]), (word_tokens[j], word_tokens[i])]: big = f"{a} {b}" if is_valid(big): noun_bigrams.append(big)
特徴として、トークンのペアを順番を変えて両方向(a b と b a)で生成しis_valid() による妥当性チェックを通過した組み合わせだけを noun_bigrams に追加するというフローで行っています。
例えば、名詞トークンに「女子校生」「誘惑」「放課後」が含まれていれば、
「女子校生 誘惑」
「誘惑 女子校生」
「女子校生 放課後」
「放課後 女子校生」
「誘惑 放課後」
「放課後 誘惑」
といったバイグラムが生成され、検索タグや関連語句として活用できます。
ここまでで、名詞同士を組み合わせた検索ワード候補を作成できるようになりました。
英単語同士のバイグラム生成
english_bigrams = for i in range(len(english_tokens)): for j in range(i + 1, len(english_tokens)): big = f"{english_tokens[i]} {english_tokens[j]}" if is_valid(big): english_bigrams.append(big)
bigram_synonyms = set() for bg in noun_bigrams + english_bigrams: parts = bg.split() mapped = [get_synonyms(p)[0] if get_synonyms(p) else p for p in parts] new_bg = ' '.join(mapped) if new_bg != bg and is_valid(new_bg): bigram_synonyms.add(new_bg)