Python 字符串计数问题:单字符查询结果错误
Python 字符串计数问题:单字符查询结果错误
在使用 Python 代码统计字符串中单词出现次数时,当输入单一字符进行查询时,结果可能出现偏差。例如,输入'a',结果显示'a'出现了15次,实际上应该只出现1次。
问题出现在字符串的处理上,将字符串直接拆成单词列表后进行查询会更准确一些。
可以使用 split() 方法将字符串按照空格拆分成单词列表,然后再进行查询。修改后的代码如下:
Mystr = 'Python is a high-level , general-purpose programming language . Its design philosophy emphasizes code ' \
'readability with the use of significant indentation . Python is dynamically typed and garbage-collected .'
words = Mystr.replace(',', '').replace('.', '').split(' ')
# words = Mystr.split(' ')
while True:
word = input('请输入要查询的单词:')
if word == 'quit':
break
count = words.count(word)
print(f'单词 {word} 在这段英文中出现了 {count} 次。')
通过将字符串拆分为单词列表,可以避免单字符查询时出现错误。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mXSi 著作权归作者所有。请勿转载和采集!