【问题标题】:Why does my word counter output the line ` 1`?为什么我的字计数器输出行`1`?
【发布时间】:2016-09-29 19:53:37
【问题描述】:

你知道为什么我在输出的第二行打印了一个“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

【问题讨论】:

  • 强制警告 - 不要使用 dict 作为变量名
  • 为什么? PyCharm 没有显示任何警告
  • @MonaJalal 它覆盖了内置的dict 函数。
  • 请注意,filter() 在 Python 3 中发生了更改,并且在其输入为字符串时不再返回字符串。 ''.join(filter(...)) 将在 Python 2 和 3 中安全地工作。

标签: python string dictionary


【解决方案1】:

因为拆分的元素之一是',',它被过滤为''

所以你在做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

【讨论】:

    【解决方案2】:

    我认为它是为“,”打印的。 您总共有 10 个单词,包括“,”(让我们将“,”视为一个单词)。 所以如果你看到所有的计数,那应该会给出答案。

    【讨论】:

    • 我认为你错了,因为我使用的是word = filter(str.isalnum, word).lower()
    • @MonaJalal 这正是它发生的原因。我不知道你为什么认为这会阻止它被放入字典。过滤后您没有检查word
    【解决方案3】:

    以下解决方案也有效:

    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]
    

    【讨论】:

    • 这正是我的回答所说的,除了它在检查之前剥离。
    • 您的回答已被接受。我刚刚写了我更正的代码
    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多