python - 将文件读取 for 循环转换为列表推导
问题描述
所以我写了一些代码来确定文本文件中最常见的 4 个单词,然后找出所有出现 2% 或更多的单词。到目前为止,我的代码运行良好。但我必须将 for 循环转换为列表推导。
到目前为止,我已经尝试过:
percent_list = [word, freq in word_counts.most_common(total) if ((freq/total)*100) >= 2.0]
对于第二个 for 循环,(请参阅下面的整个代码。)但它不起作用。这对于列表理解来说似乎有点长,因为所有在线的似乎都短了很多。
这是整个程序。总共有两个for循环。
from collections import Counter
from operator import itemgetter
STOP = ["the", "and", "in", "to", "a", "of", "at", "it", "but", "its","it's", "that", "was", "with", "as", "are", "i","this", "for", "if"]
word_counts = Counter()
with open("file.txt") as f:
for token in f.read().split():
if token.lower() not in STOP:
word_counts[token.lower()] += 1
print( word_counts.most_common(4), ":")
total = sum(word_counts.values())
print("\nWords that occur for 2% or more are: ")
for word, freq in word_counts.most_common(total):
if ((freq/total)*100) >= 2.0:
print("\n {} ".format(word))
解决方案
我认为这应该可以解决您的问题。它将返回单词和频率的元组列表。
percent_list = [(word, freq) for word,freq in word_counts.most_common(total) if ((freq/total)*100) >= 2.0]
推荐阅读
- assembly - 如何为 q35 机器制作简单的引导程序
- .net - 工作负载修复失败:`dotnet 工作负载修复 - MAUI
- javascript - dming 用户不再工作,discord.js
- haskell - 我如何证明如果 sum list = 10,那么 sum list == sum (reverse list)?
- javascript - Firebase 创建记录不适用于 PROD
- wordpress-gutenberg - 如何防止内容覆盖背景图片?
- java - JavaFX 控制器在实例化时为空
- java - 如何在单独的方法中使用主 java 文件中的字符串?
- c# - 在 NET5 asp.net core webapp 上为 Kestrel 启用 Windows 身份验证
- string - 查找特殊字符串的所有排列(递归)