python - 如何使用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
解决方案
'def' 用于创建用户定义的函数,以便稍后在脚本中调用。例如:
def printme(str):
print(str)
printme('Hello')
我现在创建了一个名为“printme”的函数,稍后我会调用它来打印字符串。这显然是一个没有意义的函数,因为它只是做“打印”函数所做的事情,但我希望这能弄清楚“def”的目的是什么!
推荐阅读
- javascript - 需要根据值对Object中的数据进行分组
- python - 将多次上传的照片整合到我的帖子中 - django
- tomcat8 - 如何修复 localhost:8080 (502 Bad Gateway) 问题
- java - 如何使用 Dagger-2 惰性注入接口?
- bash - 通过 Bash 内部获取给 eval 的扩展表达式的内容
- list - 表示提取零件的列表
- rust - 类型之间的 + 操作数是什么意思?
- vbscript - 在 VBS 中创建 txt 文件时,如何在路径中添加 %USERNAME%?
- c# - 在表单字段顶部添加水印
- javascript - 如何在 JavaScript 中拆分数组内的字符串(从全名中获取名字)