使用python计算文件中单词的频率

2024-09-19 23:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份有段落的档案。我只想计算每个单词的频率。我试过以下几种方法。但我没有得到任何输出。谁能帮帮我吗。在

dic = {}
with open("C:\\Users\\vWX442280\Desktop\\f1.txt" ,'r') as f:
    for line in f:
        l1 = line.split(" ")
        for w in l1:
            dic[w] = dic.get(w,0)+1
print ('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]))

我得到这样的输出。在

^{pr2}$

Tags: 方法inl1forwithline档案open
3条回答

一种纯python方式,无需导入任何库。更多的代码,但是我今天想写一些不好的代码(:

file = open('path/to/file.txt', 'r')
content = ' '.join(line for line in file.read().splitlines())
content = content.split(' ')
freqs = {}
for word in content:
    if word not in freqs:
        freqs[word] = 1
    else:
        freqs[word] += 1
file.close()

这使用python字典来存储单词及其出现的次数。 我知道使用with open(blah) as b:更好,但这只是为了让大家理解这个想法。` \(ツ)´´

从你的代码中,我发现了以下问题

  • for s in ll是一行文本,for循环将遍历每个字符,而不是单词
  • f.split('\n')表达式将生成一个错误,因为f是一个file对象,它没有.split()方法,string有

考虑到这一点,下面是重写代码以使其正常工作:

dic = {}
with open("f1.txt" ,'r') as f:
    for l in f:
        for w in l.split():
            dic[w] = dic.get(w,0)+1
print ('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]))

您可以使用count方法

mystring = "hello hello hello"
mystring.count("hello")  # 3

相关问题 更多 >