【发布时间】:2018-08-28 04:36:04
【问题描述】:
我是 python 新手,所以我希望你们能帮助我。目前我正在使用导入函数来获取我的输出,但我希望将 def 函数包含到这组代码中,以计算前 10 个最常见的单词。但我无法弄清楚。希望你们能帮助我。先谢谢了!!!
import collections
import re
file = open('partA', 'r')
file = file.read()
stopwords = set(line.strip() for line in open('stopwords.txt'))
stopwords = stopwords.union(set(['it', 'is']))
wordcount = collections.defaultdict(int)
"""
the next paragraph does all the counting and is the main point of difference from the original article. More on this is explained later.
"""
pattern = r"\W"
for word in file.lower().split():
word = re.sub(pattern, '', word)
if word not in stopwords:
wordcount[word] += 1
to_print = int(input("How many top words do you wish to print?"))
print(f"The most common {to_print} words are:")
mc = sorted(wordcount.items(), key=lambda k_v: k_v[1], reverse=True) [:to_print]
for word, count in mc:
print(word, ":", count)
输出: 您希望打印多少个热门词?30 最常见的30个词是: 嘿:1 那里:1 这个:1 乔伊:1 如何:1 去:1
【问题讨论】:
-
“使用import函数”和“使用def函数”是什么意思?这些都不是函数,它们是语句。他们做的事情非常不同:一个是让一个模块及其所有全局变量对您的代码可用;另一个创建一个新函数。
标签: python python-3.x