python - 词频硬件

标签 python python-3.x

编写一个程序,询问用户文件名,然后读入该文件。然后,程序应该确定文件中每个单词的使用频率。无论大小写,都应该对单词进行计数,例如 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}

关于python - 词频硬件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55739163/

相关文章:

python - 带掩码的 numpy 赋值

python - 并行遍历 numpy 数组并创建新结果数组的有效方法

Python numpy MemoryError - 将多个 CSV 文件加载到 HDF5 存储中并读入 DataFrame

python - 如何在列表中返回列表的元素?

python - 在 linux 上用 python 将文件写入 usb

python - flake8 在过滤器子句中提示 bool 比较 "=="

python - 将复杂对象打印为多行字符串

python - numpy reshape 如何使用负变量作为第二个参数

python - 注册 abc 的实现而不将其添加到 mro

python - 如何根据另一列更改数据框列中的值?