2016-06-29 2 views
0

데이터베이스에서 다른 문서를 가져오고 LDA (gensim)로 확인합니다.이 문서에는 어떤 종류의 숨은 주제가 들어 있는지 확인합니다. 이것은 꽤 잘 작동합니다. 내가하고 싶은 것은 가장 가능성있는 주제가 무엇인지 모든 문서에 대해 데이터베이스에 저장하는 것입니다. 그리고 무엇이 최선의 해결책인지 확신 할 수 없습니다. 예를 들어, 처음에는 text_column과 함께 데이터베이스에서 모든 문서의 고유 ID를 추출하고, 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 
+1

일반적으로 'SELECT id, text_column FROM table where ...'와 같이 데이터베이스의 텍스트와 함께 PK를 선택하게됩니다. 파이썬에서는 key-> value 쌍을 dict (키를 id로 함) 또는 2-tuples의 집합/배열에 넣을 수 있습니다. – wildplasser

+0

감사합니다. 나는 내 머리 속의 일들을 과장하고 있었다. 첫 번째 루프에서'documents.append (i)'로 완벽하게 작업했습니다. ('documents = documents + list (i)') 전에 select 쿼리에 id를 추가 할 때 편지에서 단어를 분리하기 시작했습니다. – student

+0

그리고이 줄은 다르다. 누군가가 stoplist에없는 word.lower()와 string에없는 단어 인 경우에는'texts = document [1] .split()에있는 단어에 대해 [word.lower() .punctuation 및 word.lower()가 additional_list에 없음] 문서의 문서]' – student

답변

0

wildplasser가 댓글을 달았 기 때문에 text_column과 함께 id를 선택하기 만하면됩니다. 이전에 시도했지만 목록에 데이터를 추가하는 방식으로 추가 처리에는 적합하지 않았습니다. 아래의 코드가 작동하고 결과적으로 가장 가능성이 높은 항목과 ID가 포함 된 표가 생성됩니다.

stop = stopwords.words('english') 

sql = """SELECT id, 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.append(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[1].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 
lda_topics = [] 
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] 
     lda_topics.append((selected_topic[0],int(t[0]))) 

cur.execute("""CREATE TABLE table_topic (id bigint PRIMARY KEY, topic int);""") 
for j in lda_topics: 
    my_id = j[1] 
    topic = j[0] 
    cur.execute("INSERT INTO table_topic (id, topic) VALUES (%s, %s)", (my_id,topic)) 
    conn.commit()