繁体   English   中英

从 Python 数据帧创建词频矩阵

[英]Creating a term frequency matrix from a Python Dataframe

我正在对一些 Twitter 数据进行一些自然语言处理。 所以我成功地加载并清理了一些推文,并将其放入下面的数据框中。

id                    text                                                                          
1104159474368024599 repmiketurner the only time that michael cohen told the truth is when he pled that he is guilty also when he said no collusion and i did not tell him to lie
1104155456019357703 rt msnbc president trump and first lady melania trump view memorial crosses for the 23 people killed in the alabama tornadoes t

问题是我试图构建一个词频矩阵,其中每一行是一条推文,每一列是所述单词出现在特定行中的值。 我唯一的问题是其他帖子提到了词频分布文本文件。 这是我用来生成上面数据框的代码

import nltk.classify
from nltk.tokenize import word_tokenize
from nltk.tokenize import wordpunct_tokenize
from nltk.corpus import stopwords
from nltk.probability import FreqDist
df_tweetText = df_tweet
#Makes a dataframe of just the text and ID to make it easier to tokenize
df_tweetText = pd.DataFrame(df_tweetText['text'].str.replace(r'[^\w\s]+', '').str.lower())

#Removing Stop words
#nltk.download('stopwords')
stop = stopwords.words('english')
#df_tweetText['text'] = df_tweetText.apply(lambda x: [item for item in x if item not in stop])
#Remove the https linkes
df_tweetText['text'] = df_tweetText['text'].replace("[https]+[a-zA-Z0-9]{14}",'',regex=True, inplace=False)
#Tokenize the words
df_tweetText

起初我尝试使用函数word_dist = nltk.FreqDist(df_tweetText['text'])但它最终会计算整个句子的值而不是行中的每个单词。

我尝试过的另一件事是使用df_tweetText['text'] = df_tweetText['text'].apply(word_tokenize)标记每个单词,然后再次调用FeqDist但这给了我一个错误,说unhashable type: 'list'

1104159474368024599 [repmiketurner, the, only, time, that, michael, cohen, told, the, truth, is, when, he, pled, that, he, is, guilty, also, when, he, said, no, collusion, and, i, did, not, tell, him, to, lie]
1104155456019357703 [rt, msnbc, president, trump, and, first, lady, melania, trump, view, memorial, crosses, for, the, 23, people, killed, in, the, alabama, tornadoes, t]

有没有其他方法可以尝试构建这个词频矩阵? 理想情况下,我希望我的数据看起来像这样

id                  |collusion | president |
------------------------------------------ 
1104159474368024599 |  1       |     0     |
1104155456019357703 |  0       |     2     |

编辑 1:所以我决定看看textmining库并重新创建他们的一个例子。 唯一的问题是它使用每条推文的一行创建术语文档矩阵。

import textmining
#Creates Term Matrix 
tweetDocumentmatrix = textmining.TermDocumentMatrix()
for column in df_tweetText:
    tweetDocumentmatrix.add_doc(df_tweetText['text'].to_string(index=False))
#    print(df_tweetText['text'].to_string(index=False))

for row in tweetDocumentmatrix.rows(cutoff=1):
    print(row)

EDIT2:所以我尝试了 SKlearn,但这种方法有效,但问题是我在我的列中发现了不应该存在的中文/日文字符。 由于某种原因,我的列也显示为数字

from sklearn.feature_extraction.text import CountVectorizer

corpus = df_tweetText['text'].tolist()
vec = CountVectorizer()
X = vec.fit_transform(corpus)
df = pd.DataFrame(X.toarray(), columns=vec.get_feature_names())
print(df)

      00  007cigarjoe  08  10  100  1000  10000  100000  1000000  10000000  \
0      0            0   0   0    0     0      0       0        0         0   
1      0            0   0   0    0     0      0       0        0         0   
2      0            0   0   0    0     0      0       0        0         0  

通过迭代每一行可能不是最佳的,但有效。 Milage 可能会根据推文的长度和正在处理的推文数量而有所不同。

import pandas as pd
from collections import Counter

# example df
df = pd.DataFrame()
df['tweets'] = [['test','xd'],['hehe','xd'],['sam','xd','xd']]

# result dataframe
df2 = pd.DataFrame()
for i, row in df.iterrows():
    df2 = df2.append(pd.DataFrame.from_dict(Counter(row.tweets), orient='index').transpose())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM