python - 词频硬件
问题描述
编写一个程序,询问用户文件名,然后读入文件。然后程序应该确定文件中每个单词的使用频率。无论大小写如何,都应计算单词,例如 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”计为单个单词。
解决方案
我们首先获取列表中的单词,更新列表以使所有单词都是小写的。您可以通过将字符串中的标点符号替换为空字符来忽略标点符号
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}
推荐阅读
- arrays - 在常见的 lisp 中,使用 '#(...) 或仅使用 #(...) 创建向量有什么区别?
- python - SQL 中的中间聚合函数和数据操作
- azure - 有没有办法使用二头肌将 Azure 防火墙连接到 Front Door 高级策略?
- swift - xcode12 如何将.md 文件的字体更改为等宽字体?
- javascript - 展平嵌套的 JSON 对象
- python - 一次将多个 tkinter 菜单项设置为“正常”的最有效方法是什么?
- python - 你如何在 Numpy 中创建一个(有时)参差不齐的数组?
- xcode - 为什么 datePicker View 的转换不能按预期工作?
- css - 根据特定事件的进度为自定义贝塞尔曲线设置动画
- rust - Rust Calamine 可选解析器在第一个空单元格处停止读取行