首页 > 解决方案 > 在列表理解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

标签: pythonlistif-statement

解决方案


为什么不只使用正则表达式和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)

推荐阅读