python - 在列表理解python中得到不正确的结果
问题描述
我在下面的代码中做错了什么。我有 if 语句来避免任何数字,但它们仍然出现在文本中,并且文本中也包含空字符串。我想要的最后一个是避免uninteresting_words
列表中的单词。
def calculate_frequencies(file_contents):
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]
# Split the file_contents into list of words
words = file_contents.split()
# Remove the punctuations from the text
table = str.maketrans("", "", string.punctuation)
stripped = [word.translate(table)
for word in words
if word.isdigit() != True # Word should not be a digit
and word # There shouldn't be any space
and (word.lower() not in uninteresting_words) # check on each word if it's not present in un_interesting words
]
# Count words
word_count = {}
for word in stripped:
if word in word_count.keys():
word_count[word] += 1
else:
word_count[word] = 1
解决方案
为什么不只使用正则表达式和collections.Counter
:(您也可以uninteresting_words
设置一组以加快查找速度)
import re
from collections import Counter
uninteresting_words = {"the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \
"we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
"their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
"have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
"all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"}
word_count = Counter(word for word in re.finditer('/\b[^\d\W]+\b/g', words) if word not in uninteresting_words)
推荐阅读
- sql-server - SQL Server 2014 意外服务停止
- php - 405方法不允许重定向错误laravel为什么
- hibernate - 为什么Hibernate偶尔会在persist中执行select currval?
- azure-pipelines - 将两个 GetMetadataDB 活动输出值发送到 Foreach 活动
- java - 重新建立与主机的连接后,侦听器不提取数据
- node.js - 猫鼬 - updateMany
- javascript - 如何在 React-Native 中连接到 MQTT 代理?
- html - beautiful soup unable to find elements from website
- kotlin - Why data classes in Kotlin cannot be marked with inner modifier?
- android - 如何在每天 23:59 向服务器发送数据?