繁体   English   中英

在python中查找文本文件中每个单词的频率

[英]To find frequency of every word in text file in python

我想在我的文本文件中找到所有单词的频率,以便我可以从中找出最常出现的单词。 有人可以帮助我使用该命令。

import nltk
text1 = "hello he heloo hello hi " // example text
 fdist1 = FreqDist(text1) 

我使用了上面的代码,但问题是它没有给出词频,而是显示每个字符的频率。 我也想知道如何使用文本文件输入文本。

就其价值而言,NLTK 似乎对这项任务有点过分。 以下将按从高到低的顺序为您提供词频。

from collections import Counter
input_string = [...] # get the input from a file
word_freqs = Counter(input_string.split())

我看到您正在使用该示例并看到您所看到的相同内容,为了使其正常工作,您必须按空格拆分字符串。 如果你不这样做,它似乎会计算每个字符,这就是你所看到的。 这将返回每个单词的正确计数,而不是字符。

import nltk

text1 = 'hello he heloo hello hi '
text1 = text1.split(' ')
fdist1 = nltk.FreqDist(text1)
print (fdist1.most_common(50))

如果您想从文件中读取并获取字数,您可以这样做:

输入文件

hello he heloo hello hi
my username is heinst
your username is frooty

蟒蛇代码

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))

nltk 书中的text1是标记(单词、标点符号)的集合,这与您的代码示例中的text1是字符串(Unicode 代码点的集合)不同:

>>> from nltk.book import text1
>>> text1
<Text: Moby Dick by Herman Melville 1851>
>>> text1[99] # 100th token in the text
','
>>> from nltk import FreqDist
>>> FreqDist(text1)
FreqDist({',': 18713, 'the': 13721, '.': 6862, 'of': 6536, 'and': 6024,
          'a': 4569, 'to': 4542, ';': 4072, 'in': 3916, 'that': 2982, ...})

如果您的输入确实是空格分隔的单词,那么要查找频率,请使用@Boa 的回答

freq = Counter(text_with_space_separated_words.split())

注意: FreqDist是一个Counter但它也定义了其他方法,例如.plot()

如果您想改用nltk标记器:

#!/usr/bin/env python3
from itertools import chain
from nltk import FreqDist, sent_tokenize, word_tokenize # $ pip install nltk

with open('your_text.txt') as file:
    text = file.read()
words = chain.from_iterable(map(word_tokenize, sent_tokenize(text)))
freq = FreqDist(map(str.casefold, words))
freq.pprint()
# -> FreqDist({'hello': 2, 'hi': 1, 'heloo': 1, 'he': 1})

sent_tokenize()将文本标记为句子。 然后word_tokenize每个句子标记为单词。 有很多方法可以在nltk标记文本。

为了将频率和单词作为字典,以下代码将是有益的:

import nltk
from nltk.tokenize import word_tokenize  

for f in word_tokenize(inputSentence):  
     dict[f] = fre[f]                                                  

print dict

我认为下面的代码对您以字典形式获取文件中每个单词的频率很有用

myfile=open('greet.txt')
temp=myfile.read()
x=temp.split("\n")
y=list()
for item in x:
   z=item.split(" ")
   y.append(z)
count=dict()
for name in y:
   for items in name:
       if items not in count:`enter code here`
        count[items]=1
      else:
        count[items]=count[items]+1
print(count)

暂无
暂无

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

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