作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
你知道为什么我在输出的第二行打印了一个“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/
我是一名优秀的程序员,十分优秀!