gpt4 book ai didi

python - 为什么我的字计数器输出行 ` 1` ?

转载 作者:行者123 更新时间:2023-11-28 21:46:42 25 4
gpt4 key购买 nike

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

关于python - 为什么我的字计数器输出行 ` 1` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com