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

Mon*_*lal 2 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]
Run Code Online (Sandbox Code Playgroud)

结果是:

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

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

Mor*_*app 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
Run Code Online (Sandbox Code Playgroud)