我正在尝试创建一个打开文本文件的函数,对单词进行计数,然后以百分比形式返回前7个单词。但是,当我使用“return”运行代码时,它只检索第一个值,但“print”给出了我需要的内容+“无”。
def count_wfrequency(fname):
with open(fname,"r") as f:
dictionary = dict()
for line in f:
line = line.rstrip()
delaorden = line.split()
for word in delaorden:
dictionary[word] = dictionary.get(word,0) + 1
tmp = list()
for key, value in dictionary.items():
tmp.append((value, key))
tmp.sort(reverse=True)
for value, key in tmp[:7]:
b = ("{0:.0f}%".format(value / len(tmp)* 100))
print(key, b, end=", ")
the 9%, to 6%, of 5%, and 4%, in 3%, a 3%, would 2%, Frequency of words: None
我做错了什么?
编辑:为了澄清,我想做到这样,它打印出“单词的频率:9%,到6%......等等。
尝试使用这样的功能:
if args.word_frequency:
print("Frequency of words: {}".format(funk.count_wfrequency(args.filename)))