私はデータベースとは別のドキュメントを取っていますが、LDA(gensim)で調べると、これらのドキュメントにはどのような潜在的なトピックがありますか。これはかなりうまくいく。私がしたいのは、最も可能性の高いトピックが何であるかをすべての文書のデータベースに保存することです。そして、私はそれに最適な解決策が何であるか分かりません。たとえば、最初に、text_columnと一緒にデータベースからすべてのドキュメントの一意のIDを抽出し、最終的にどのトピック番号に属しているかを私が知っているように処理します。あるいは、私は最後の部分で文書やそのトピックを印刷しなければならないかもしれません。しかし、私はそれをデータベースに戻す方法を知らない。 text_columnと文書を比較し、対応するトピック番号を割り当てることによって?コメントに感謝します。LDA gensim。 Postgresデータベースをすべての文書の正しいトピック番号で更新するには?
stop = stopwords.words('english')
sql = """SELECT text_column FROM table where NULLIF(text_column, '') IS NOT NULL;"""
cur.execute(sql)
dbrows = cur.fetchall()
conn.commit()
documents = []
for i in dbrows:
documents = documents + list(i)
# remove all the words from the stoplist and tokenize
stoplist = stopwords.words('english')
additional_list = set("``;''".split(";"))
texts = [[word.lower() for word in document.split() if word.lower() not in stoplist and word not in string.punctuation and word.lower() not in additional_list]
for document in documents]
# remove words that appear less or equal of 2 times
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) <= 2)
texts = [[word for word in text if word not in tokens_once]
for text in texts]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
my_num_topics = 10
# lda itself
lda = ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=my_num_topics)
corpus_lda = lda[corpus]
# print the most contributing words for selected topics
for top in lda.show_topics(my_num_topics):
print top
# print the most probable topic and the document
for l,t in izip(corpus_lda,documents):
selected_topic = max(l,key=lambda item:item[1])
if selected_topic[1] != 1/my_num_topics:
selected_topic_number = selected_topic[0]
print selected_topic
print t
通常はテーブルFROM text_column、IDを選択し 'のようなデータベースからのテキストと一緒にPKを選択することになります...'。 Pythonでは、key-> valueの組をdict(キーをidにする)または2組の集合/配列に入れることができます。 – wildplasser
ありがとうございました!私は私の頭の中で物事を過密していただけだった。最初のループで 'documents.append(i)'と完全に連携しました。私が以前に行っていたやり方( 'documents = documents + list(i)')は、selectクエリにidを追加するときに、文字を単語に分割し始めました。 – student
そして、この行は異なっています。ちょうど誰かがストップリストにない単語と文字列にない単語 'texts = [[1] .split()内の単語に対して[word.lower() .punctuationとword.lower()は追加リストにありません] ドキュメントのドキュメント] '' – student