Python文字处理:NLTK和 pandas [英] Python text processing: NLTK and pandas
问题描述
我正在寻找一种有效的方法来用Python构造可与额外数据一起使用的术语文档矩阵.
I'm looking for an effective way to construct a Term Document Matrix in Python that can be used together with extra data.
我有一些带有其他一些属性的文本数据.我想对文本进行一些分析,并且希望能够将从文本中提取的功能(例如单个单词标记或LDA主题)与其他属性相关联.
I have some text data with a few other attributes. I would like to run some analyses on the text and I would like to be able to correlate features extracted from text (such as individual word tokens or LDA topics) with the other attributes.
我的计划是将数据作为熊猫数据框加载,然后每个响应将代表一个文档.不幸的是,我遇到了一个问题:
My plan was load the data as a pandas data frame and then each response will represent a document. Unfortunately, I ran into an issue:
import pandas as pd
import nltk
pd.options.display.max_colwidth = 10000
txt_data = pd.read_csv("data_file.csv",sep="|")
txt = str(txt_data.comment)
len(txt)
Out[7]: 71581
txt = nltk.word_tokenize(txt)
txt = nltk.Text(txt)
txt.count("the")
Out[10]: 45
txt_lines = []
f = open("txt_lines_only.txt")
for line in f:
txt_lines.append(line)
txt = str(txt_lines)
len(txt)
Out[14]: 1668813
txt = nltk.word_tokenize(txt)
txt = nltk.Text(txt)
txt.count("the")
Out[17]: 10086
请注意,在两种情况下,文本都以这样的方式进行处理:除空格,字母和..!之外,仅包含其他任何内容!被删除(为简单起见).
Note that in both cases, text was processed in such a way that only the anything but spaces, letters and ,.?! was removed (for simplicity).
如您所见,pandas字段转换为字符串会返回较少的匹配项,并且字符串的长度也较短.
As you can see a pandas field converted into a string returns fewer matches and the length of the string is also shorter.
有什么办法可以改善上面的代码?
Is there any way to improve the above code?
此外,str(x)
从注释中创建1个大字符串,而[str(x) for x in txt_data.comment]
创建一个不能分解为单词袋的列表对象.生成将保留文档索引的nltk.Text
对象的最佳方法是什么?换句话说,我正在寻找一种创建术语文档矩阵的方法,R与tm
包中的TermDocumentMatrix()
等效.
Also, str(x)
creates 1 big string out of the comments while [str(x) for x in txt_data.comment]
creates a list object which cannot be broken into a bag of words. What is the best way to produce a nltk.Text
object that will retain document indices? In other words I'm looking for a way to create a Term Document Matrix, R's equivalent of TermDocumentMatrix()
from tm
package.
非常感谢.
推荐答案
使用pandas
DataFrame
的好处是可以将nltk
功能应用于每个row
,如下所示:
The benefit of using a pandas
DataFrame
would be to apply the nltk
functionality to each row
like so:
word_file = "/usr/share/dict/words"
words = open(word_file).read().splitlines()[10:50]
random_word_list = [[' '.join(np.random.choice(words, size=1000, replace=True))] for i in range(50)]
df = pd.DataFrame(random_word_list, columns=['text'])
df.head()
text
0 Aaru Aaronic abandonable abandonedly abaction ...
1 abampere abampere abacus aback abalone abactor...
2 abaisance abalienate abandonedly abaff abacina...
3 Ababdeh abalone abac abaiser abandonable abact...
4 abandonable abandon aba abaiser abaft Abama ab...
len(df)
50
txt = df.text.apply(word_tokenize)
txt.head()
0 [Aaru, Aaronic, abandonable, abandonedly, abac...
1 [abampere, abampere, abacus, aback, abalone, a...
2 [abaisance, abalienate, abandonedly, abaff, ab...
3 [Ababdeh, abalone, abac, abaiser, abandonable,...
4 [abandonable, abandon, aba, abaiser, abaft, Ab...
txt.apply(len)
0 1000
1 1000
2 1000
3 1000
4 1000
....
44 1000
45 1000
46 1000
47 1000
48 1000
49 1000
Name: text, dtype: int64
因此,对于每个row
条目,您都会获得.count()
:
As a result, you get the .count()
for each row
entry:
txt = txt.apply(lambda x: nltk.Text(x).count('abac'))
txt.head()
0 27
1 24
2 17
3 25
4 32
然后您可以使用以下方法求和:
You can then sum the result using:
txt.sum()
1239
这篇关于Python文字处理:NLTK和 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!