编写一个程序,要求用户提供一个文件名,然后读取该文件。然后,程序应该确定文件中每个单词的使用频率。无论是哪种情况,单词都应该被计算,例如垃圾邮件和垃圾邮件都被计算为相同的单词。你应该忽略标点符号。然后,程序应该输出单词和每个单词使用的频率。输出应该按照最频繁的单词和最不频繁的单词进行排序。
我遇到的唯一问题是让代码将" 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”。
发布于 2019-04-18 05:10:01
我们从获取列表中的单词开始,更新列表,使所有单词都是小写的。可以忽略标点符号,方法是将字符串中的标点符号替换为空字符。
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}发布于 2019-04-18 05:32:42
你可以用计数器就像这样,
from collections import Counter
import re
sentence = 'Egg ? egg Bird, Goat afterDoubleSpace\nnewline'
# some punctuations (you can add more here)
punctuationsToBeremoved = ",|\n|\?"
#to make all of them in lower case
sentence = sentence.lower()
#to clean up the punctuations
sentence = re.sub(punctuationsToBeremoved, " ", sentence)
# getting the word list
words = sentence.split()
# printing the frequency of each word
print(Counter(words)) https://stackoverflow.com/questions/55739163
复制相似问题