【问题标题】:how to use the def function如何使用def函数
【发布时间】: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


【解决方案1】:

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

def printme(str):
    print(str)


printme('Hello')

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

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2018-03-23
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多