python查txt单词次数_在python中查找文本文件中每个单词的频率

I want to find frequency of all words in my text file so that i can find out most frequently occuring words from them.

Can someone please help me the command to be used for that.

import nltk

text1 = "hello he heloo hello hi " // example text

fdist1 = FreqDist(text1)

I have used above code but problem is that it is not giving word frequency,rather it is displaying frequency of every character.

Also i want to know how to input text using text file.

解决方案

I saw you were using the example and saw the same thing you were seeing, in order for it to work properly, you have to split the string by spaces. If you do not do this, it seems to count each character, which is what you were seeing. This returns the proper counts of each word, not character.

import nltk

text1 = 'hello he heloo hello hi '

text1 = text1.split(' ')

fdist1 = nltk.FreqDist(text1)

print (fdist1.most_common(50))

If you want to read from a file and get the word count, you can do it like so:

input.txt

hello he heloo hello hi

my username is heinst

your username is frooty

python code

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值