如何用Python 3修改词频统计的列表输出格式?
解决方法
首先,你需要确保导入collections模块中的Counter(原代码可能遗漏了这一步),然后将most_common()返回的元组列表转换为字典,并按照你期望的格式输出。以下是修改后的完整代码:
from collections import Counter # 必须导入Counter才能使用 mostFrequent = [] # 存储文件内容的列表 fileName = input("Enter a file name: ") with open(fileName, "r") as i: # 读取文件每一行并拆分单词存入列表 for line in i: mostFrequent.extend(line.split()) wordCounter = Counter(mostFrequent) # 统计每个单词的出现次数 topMostFrequent = wordCounter.most_common(10) # 获取出现次数前10的单词 # 将元组列表转换为字典 top_word_dict = dict(topMostFrequent) # 构造符合要求的输出格式 output_str = "{ " + ", ".join([f"{word} : {count}" for word, count in top_word_dict.items()]) + " }" print(output_str)
关键改动说明:
- 补充
from collections import Counter:Counter是collections模块下的工具类,必须显式导入才能使用。 - 用
dict(topMostFrequent)转字典:most_common()返回的是[(单词, 次数), ...]格式的列表,直接传入dict()就能生成键为单词、值为次数的字典。 - 手动构造输出字符串:默认打印字典时键会带引号,通过列表推导式将每个键值对转为
"单词 : 次数"的格式,再用,连接,最后加上大括号,就能得到你想要的无引号键的输出样式。
如果不想额外转换字典,也可以直接处理topMostFrequent元组列表生成输出:
# 直接处理元组列表,跳过转字典步骤 output_str = "{ " + ", ".join([f"{word} : {count}" for word, count in topMostFrequent]) + " }" print(output_str)
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

