首页 > 解决方案 > 如何使用def函数

问题描述

我是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

标签: pythonpython-3.x

解决方案


'def' 用于创建用户定义的函数,以便稍后在脚本中调用。例如:

def printme(str):
    print(str)


printme('Hello')

我现在创建了一个名为“printme”的函数,稍后我会调用它来打印字符串。这显然是一个没有意义的函数,因为它只是做“打印”函数所做的事情,但我希望这能弄清楚“def”的目的是什么!


推荐阅读