首页 > 解决方案 > 词频硬件

问题描述

编写一个程序,询问用户文件名,然后读入文件。然后程序应该确定文件中每个单词的使用频率。无论大小写如何,都应计算单词,例如 Spam 和 spam 都将被视为同一个单词。你应该忽略标点符号。然后程序应该输出单词以及每个单词的使用频率。输出应该按最频繁的单词到最不频繁的单词排序。

我遇到的唯一问题是让代码将“The”和“the”算作同一件事。代码将它们视为不同的单词。

userinput = input("Enter a file to open:")
if len(userinput) < 1 : userinput = 'ran.txt'
f = open(userinput)
di = dict()
for lin in f:
    lin = lin.rstrip()
    wds = lin.split()
    for w in wds:
        di[w] = di.get(w,0) + 1
    lst = list()
    for k,v in di.items():
       newtup = (v, k)
       lst.append(newtup)
lst = sorted(lst, reverse=True)
print(lst)

需要将“the”和“The”计为单个单词。

标签: pythonpython-3.x

解决方案


我们首先获取列表中的单词,更新列表以使所有单词都是小写的。您可以通过将字符串中的标点符号替换为空字符来忽略标点符号


punctuations = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
s = "I want to count how many Words are there.i Want to Count how Many words are There"

for punc in punctuations:
    s = s.replace(punc,' ')

words = s.split(' ')
words = [word.lower() for word in words]

然后我们遍历列表,并更新频率图。

freq = {}

for word in words:
    if word in freq:
        freq[word] += 1
    else:
        freq[word] = 1
print(freq)
#{'i': 2, 'want': 2, 'to': 2, 'count': 2, 'how': 2, 'many': 2, 
#'words': 2, 'are': #2, 'there': 2}

推荐阅读