python中不需要计算空字符串(重复)

python中不需要计算空字符串(重复),python,Python,这个程序的目的是数一数文章中的每个单词,并记下频率。不幸的是,程序也在计算空字符串。我的代码是: def build_map( in_file, word_map ): # Receives an input file and an empty dictionary for line in in_file: # Splits each line at blank space and turns it into # a list. word_list

这个程序的目的是数一数文章中的每个单词,并记下频率。不幸的是,程序也在计算空字符串。我的代码是:

def build_map( in_file, word_map ):
# Receives an input file and an empty dictionary


    for line in in_file:

    # Splits each line at blank space and turns it into
    # a list.
        word_list = line.split()



        for word in word_list: 
            word= word.strip().strip(string.punctuation).lower()#program revised           
            if word!='':

            # Within the word_list, we are stripping empty space
            # on both sides of each word and also stripping any
            # punctuation on both side of each word in the list.
            # Then, it turns each word to the lower case to avoid
            # counting 'THE' and 'the' as two different words.

                add_word( word_map, word)

如果有人能看一下代码并解释一下,为什么它仍然在计算空字符串,我将不胜感激。除此之外,其他一切都很好。谢谢(修改了代码,现在工作正常)。

您正在检查单词是否为空,然后删除空格和标点符号。颠倒这些操作的顺序。

它起作用了。感谢您仔细阅读我的代码并找出问题所在。定义“word_map=collections.defaultdict(int)”,则无需初始化一个新单词使其计数为零。也就是说,每次调用add_word都可以替换为word_map[word]+=1。您需要“导入集合”。您应该能够将display_map中的word_list变量替换为“word_map.items()”(并删除该函数的前3行)。您可能还可以使用集合模块中的计数器