Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用def功能_Python_Python 3.x - Fatal编程技术网

Python 如何使用def功能

Python 如何使用def功能,python,python-3.x,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 =

我是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
going:1“def”用于创建用户定义的函数,以便以后在脚本中调用。例如:

def printme(str):
    print(str)


printme('Hello')

我现在创建了一个名为“printme”的函数,稍后我会调用它来打印字符串。这显然是一个毫无意义的函数,因为它只做“print”函数所做的事情,但我希望这澄清了“def”的用途

“使用导入功能”和“使用def功能”是什么意思?这两个都不是函数,它们都是语句。它们做了非常不同的事情:一个是使一个模块及其所有全局变量可用于您的代码;另一个创建了一个新函数。请看这里: