在python中不需要计算空字符串(repeat)

2024-04-20 14:32:34 发布

您现在位置: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 = 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)

如果有人能看一下代码并解释一下为什么它还在数空字符串,我会非常感激。除此之外,其他一切都很好。谢谢(修改了代码,现在可以正常工作了)。你知道吗


Tags: andthe字符串代码in程序anmap