我有一份有段落的档案。我只想计算每个单词的频率。我试过以下几种方法。但我没有得到任何输出。谁能帮帮我吗。在
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}$
一种纯python方式,无需导入任何库。更多的代码,但是我今天想写一些不好的代码(:
这使用python字典来存储单词及其出现的次数。 我知道使用
with open(blah) as b:
更好,但这只是为了让大家理解这个想法。` \(ツ)´´从你的代码中,我发现了以下问题
for s in l
:l
是一行文本,for循环将遍历每个字符,而不是单词f.split('\n')
表达式将生成一个错误,因为f
是一个file对象,它没有.split()
方法,string有考虑到这一点,下面是重写代码以使其正常工作:
您可以使用
count
方法相关问题 更多 >
编程相关推荐