import nltk
text1 = 'hello he heloo hello hi '
text1 = text1.split(' ')
fdist1 = nltk.FreqDist(text1)
print (fdist1.most_common(50))
如果要读取文件并获取字数,可以这样做:
input.txt
hello he heloo hello hi
my username is heinst
your username is frooty
python代码
import nltk
with open ("input.txt", "r") as myfile:
data=myfile.read().replace('\n', ' ')
data = data.split(' ')
fdist1 = nltk.FreqDist(data)
print (fdist1.most_common(50))
我看到你在用这个例子,看到了和你看到的一样的东西,为了让它正常工作,你必须用空格分开字符串。如果你不这样做,它似乎计数每个字符,这是你看到的。这将返回每个单词的正确计数,而不是字符。
如果要读取文件并获取字数,可以这样做:
input.txt
python代码
nltk book中的
text1
是标记(单词、标点符号)的集合,与代码示例中的text1
是字符串(Unicode代码点的集合)不同:如果您的输入确实是空格分隔的单词,那么要查找频率,请使用@Boa's answer:
注:
FreqDist
是一个Counter
,但它还定义了其他方法,如.plot()
。如果要改用
nltk
标记器:sent_tokenize()
将文本标记为句子。然后word_tokenize
将每个句子标记为单词。There are many ways to tokenize text in ^{就它的价值而言,NLTK似乎对这项任务来说是过分的。下面将按从高到低的顺序为您提供单词频率。
相关问题 更多 >
编程相关推荐