【发布时间】:2018-09-23 07:37:27
【问题描述】:
我有一个脚本,用于计算名为 alice 的文本文件中的单词数。从https://developers.google.com/edu/python/dict-files 开始练习,我了解它是如何工作的,但此处显示的一个例外是:
def get_count(word_count_tuple):
return word_count_tuple[1]
我的理解是这个函数在物品被排序时被调用并且它们是按照'get_count'的值排序的 'get_count' 有参数'word_count_tuple',在任何阶段都没有使用/分配,并且返回'word_count_tuple1'。 有人可以解释这里发生了什么,以及它是如何工作的,因为我认为函数必须传递一个参数值,或者有一个默认值,而这没有。还是它以某种方式与密钥一起分配而我错过了它?
这是完整的代码:
def word_count_dict(filename):
word_count = {}
input_file = open(filename, "r")
for line in input_file:
words = line.split()
for word in words:
word = word.lower()
if not word in word_count:
word_count[word] = 1
else:
word_count[word] += 1
input_file.close()
return(word_count)
def get_count(word_count_tuple):
return word_count_tuple[1]
def print_top(filename):
word_count = word_count_dict(filename)
items = sorted(word_count.items(), key = get_count, reverse = True)
for item in items[:20]:
print (item[0], item[1])
def main():
filename = "alice.txt"
print_top(filename)
if __name__ == '__main__':
main()
【问题讨论】:
标签: python python-3.7