首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场

词频HW
EN

Stack Overflow用户
提问于 2019-04-18 04:28:34
回答 2查看 65关注 0票数 1

编写一个程序,要求用户提供一个文件名,然后读取该文件。然后,程序应该确定文件中每个单词的使用频率。无论是哪种情况,单词都应该被计算,例如垃圾邮件和垃圾邮件都被计算为相同的单词。你应该忽略标点符号。然后,程序应该输出单词和每个单词使用的频率。输出应该按照最频繁的单词和最不频繁的单词进行排序。

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

代码语言:javascript
运行
复制
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”。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-18 05:10:01

我们从获取列表中的单词开始,更新列表,使所有单词都是小写的。可以忽略标点符号,方法是将字符串中的标点符号替换为空字符。

代码语言:javascript
运行
复制
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]

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

代码语言:javascript
运行
复制
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}
票数 1
EN

Stack Overflow用户

发布于 2019-04-18 05:32:42

你可以用计数器就像这样,

代码语言:javascript
运行
复制
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)) 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55739163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档