word2vecで名詞のみかつリスト化された文章から分散表現取得。
gensim のword2vecを使用し
分散表現はPC にファイルとして保存したいです。
python3
1from pymongo import MongoClient 2from bs4 import BeautifulSoup 3import MeCab 4mecab = MeCab.Tagger ('/usr/local/lib/mecab/dic/mecab-ipadic-neologd') 5def main(): 6 recipes = [] 7 client = MongoClient('localhost', 27017) 8 db = client.html.cookpad_html 9 collection = db.test_collection 10 htmls = list(db.find().limit(1)) 11 recipes = [] 12 for num, html in enumerate(htmls): 13 soup = BeautifulSoup(html["html"], 'lxml') 14 for steps in soup.find_all(attrs={"class": "step_text"}): 15 node = mecab.parseToNode(steps.get_text()) 16 17 while node: 18 if node.feature.split(",")[0] == '名詞': 19 recipes.append(node.feature.split(",")[6]) 20 node = node.next 21 recipes = list(set(recipes)) 22 print(recipes) 23 24if __name__ == '__main__': 25 main() 26 27text = 'main()' 28file = open('text_file_name.txt', 'w') 29file.write(text) 30file.close() 31 32from janome.tokenizer import Tokenizer 33from gensim.models import word2vec 34# 単語の分かち書き&スペースで区切る 35 36import codecs 37 38text_space = "" 39t = Tokenizer() 40with codecs.open('text_file_name.txt', 'r', 'utf-8') as f: 41 txt = f.read() 42for token in t.tokenize(txt, stream=True): 43 text_space += token.surface 44 text_space += " " 45# ファイル書き込み 46with codecs.open('wakachigaki_file_name.txt', 'w', 'utf-8') as file: 47 file.write(text_space) 48# Word2vecのモデルの作成 49sentences = word2vec.LineSentence('wakachigaki_file_name.txt') 50model = word2vec.Word2Vec(sentences, 51 sg=1, 52 size=100, 53 min_count=1, 54 window=10, 55 hs=1, 56 negative=0) 57model.save('model_name.model') 58# モデルの読み込みと類義語の計算 59model = word2vec.Word2Vec.load("model_name.model") 60 61 62 63model.most_similar(positive="単語", topn=10) 64
"word '単語' not in vocabulary"エラーコードです。
急ぎで誰か教えて下さい。