我需要使用NLTK包计算一些语料库中的单词数(单词出现)
这是我的语料库:
corpus = PlaintextCorpusReader('C:\DeCorpus', '.*')
以下是我如何获取每个文档的总字数:
cfd_appr = nltk.ConditionalFreqDist(
(textname, num_appr)
for textname in corpus.fileids()
for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])
(我手动将字符串拆分为单词,不知何故,它比使用corpus.words()
效果更好,但问题仍然是一样的,因此与此无关)。通常,这会做相同(错误)的工作:
cfd_appr = nltk.ConditionalFreqDist(
(textname, num_appr)
for textname in corpus.fileids()
for num_appr in [len(w) for w in corpus.words(fileids=textname)])
这是我通过键入cfd.appr.tabulate()
得到的结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
2022.12.06_Bild 2.txt 3 36 109 40 47 43 29 29 33 23 24 12 8 6 4 2 2 0 0 0 0
2022.12.06_Bild 3.txt 2 42 129 59 57 46 46 35 22 24 17 21 13 5 6 6 2 2 2 0 0
2022.12.06_Bild 4.txt 3 36 106 48 43 32 38 30 19 39 15 14 16 6 5 8 3 2 3 1 0
2022.12.06_Bild 5.txt 1 55 162 83 68 72 46 24 34 38 27 16 12 8 8 5 9 3 1 5 1
2022.12.06_Bild 6.txt 7 69 216 76 113 83 73 52 49 42 37 20 19 9 7 5 3 6 3 0 1
2022.12.06_Bild 8.txt 0 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
但这些是不同长度的单词数量。我需要的只是这个(只有一种类型的项目(文本)应按字数计算):
2022.12.06_Bild 2.txt 451.0
2022.12.06_Bild 3.txt 538.0
2022.12.06_Bild 4.txt 471.0
2022.12.06_Bild 5.txt 679.0
2022.12.06_Bild 6.txt 890.0
2022.12.06_Bild 8.txt 3.0
dtype: float64
也就是说,不同长度的所有单词的总和(或使用DataFrame(cfd_appr).transpose().sum(axis=1)
组成的列的总和)(顺便说一下,如果有某种方法为该列设置一个名称,这也是一种解决方案,但是.rename({None: 'W. appear.'}, axis='columns')
不起作用,并且解决方案通常不够清楚
所以,我需要的是:
1
2022.12.06_Bild 2.txt 451.0
2022.12.06_Bild 3.txt 538.0
2022.12.06_Bild 4.txt 471.0
2022.12.06_Bild 5.txt 679.0
2022.12.06_Bild 6.txt 890.0
2022.12.06_Bild 8.txt 3.0
非常感谢您的帮助
让我们首先尝试使用臭名昭著的BookCorpus复制表,并使用目录结构:
代码:
然后熊猫的咀嚼部分:
最后,要访问索引系列,例如:
或者
我鼓励使用上面的解决方案,这样您就可以使用DataFrame进一步操作数字,但是如果您真正需要的只是每行的列数,那么请尝试以下方法
如果需要避免使用pandas并直接使用CFD中的值,那么您必须使用
ConditionalFreqDist.values()
并仔细遍历它如果我们这样做:
我们将看到一个FreqDist列表,每个都对应于键(在本例中为文件名):
因为我们知道FreqDist is a subclass of collections.Counter object,如果我们对每个计数器对象的值求和,我们将得到:
输出与上面
df.sum(axis=1)
相同的值总而言之:
好吧,这里是实际需要的:
首先,获取不同长度的单词数(就像我之前做的那样):
然后将import
DataFrame
添加为pd
,并将to_frame(1)
添加到我通过对列求和得到的dtype: float64
序列中:就这样。然而,如果有人知道如何在
cfd_appr
的定义中求和,那将是更优雅的解决方案相关问题 更多 >
编程相关推荐