[英]What is the difference between two codes that count words in a text?
您好,我试图计算文本中的单词,但出现了问题。
如果我写这样的代码
def popular_words(text:str, list:list)-> dict:
text=text.lower()
splited_text=text.split()
answer={}
for word in list:
answer[word]=splited_text.count(word)
return answer
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new''', ['i', 'was', 'three', 'near']))
' 结果是 {'i': 4, 'was': 3, 'three': 0, 'near': 0}
很好,但是如果我编写代码而不拆分文本,例如
def popular_words(text:str, list:list)-> dict:
text=text.lower()
answer={}
for word in list:
answer[word]=text.count(word)
return answer
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new''', ['i', 'was', 'three', 'near']))
'
结果是
{'i': 4, 'was': 3, '三': 0, 'near': 1}
所以计算“近”时有错误。 我认为这是因为第二个代码也算作“接近”,但我无法理解第一个和第二个代码的结果不同。 你们能解释一下结果不同的原因吗?
没有split
的版本计算字符串中的子字符串。 因此,找到“近”。 拆分时,您现在在列表中查找字符串 - 意味着匹配必须是精确的,并且“near”不匹配列表中的“nearly”字符串。
正如@MattDMo 所说,使用list
(或任何其他关键字或内置关键字)作为变量名是一个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.