如何使用def功能

时间:2018-08-27 19:41:56

标签: python python-3.x

我是python的新手,所以我希望你们能帮助我。目前,我正在使用import函数获取我的输出,但是我希望将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

1 个答案:

答案 0 :(得分:0)

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

def printme(str):
    print(str)


printme('Hello')

我现在创建了一个名为“ printme”的函数,稍后将其调用以打印字符串。显然,这是没有意义的功能,因为它只执行“打印”功能,但是我希望这可以弄清楚“ def”的目的是什么!