为什么我的单词计数器输出“1”行?

时间:2016-05-31 17:13:30

标签: python string dictionary

你知道为什么我有一个" 1"打印在第二行输出?

def word_map(string):
    dict = {}
    for word in string.split():
        word = filter(str.isalnum, word).lower()
        word = word.split()
        if word in dict:
            dict[word] +=1
        else:
            dict[word] = 1
    return dict

dict = word_map("This is a string , this is another string too")
for k in dict:
    print k, dict[k]

结果是:

a 1
 1
string 2
this 2
is 2
too 1
another 1

Process finished with exit code 0

3 个答案:

答案 0 :(得分:5)

因为拆分的其中一个元素','会被过滤到''

所以你正在做dict[''] = 1

假设您正在尝试计算句子中的单词,您需要在过滤后或在打印时检查单词是否有效。例如,这对你有用。

def word_map(string):
    word_dict = {}
    for word in string.split():
        word = ''.join(filter(str.isalnum, word)).lower()
        if word.strip():
            if word in word_dict:
                word_dict[word] +=1
            else:
                word_dict[word] = 1
    return word_dict

答案 1 :(得分:0)

我认为它是为","打印的。 你总共有10个单词,包括"," (让我们考虑","作为一个词)。 所以如果你看到所有的计数,那就应该给出答案。

答案 2 :(得分:0)

以下解决方案也有效:

def word_map(string):
    word_dict = {}
    for word in string.split():
        word = filter(str.isalnum, word).lower()
        word = word.strip()
        if word != '':
            if word in word_dict.keys():
                word_dict[word] +=1
            else:
                word_dict[word] = 1
    return word_dict

my_dict= word_map("This is a string , this is another string too")
for k in my_dict:
    print k, my_dict[k]