如何在python3中精确计算字符串中的单词?

问题描述 投票:-2回答:2

所以我想要精确计算python中“100”的出现次数。我的示例代码:

a = " I love 1000 and 100 dollars."
b = a.count("100")
print(b)

结果是2,但我只想要它是1。

2
[Finished in 0.1s]

那有什么基本的提示吗?我只是一个初学者学习python。

python count
2个回答
1
投票

如果要计算字符串中的子字符串,则正则表达式模块re将非常有用:

import re
len(re.findall(r'\b100\b', a)) # prints 1

len返回re.findall()发现的次数,即1

100替换为您想要计算的特定子字符串:

b = len(re.findall(r'\bI love\b', a))
>>> b
1

从这个答案Find substring in string but only if whole words?借来的技术


1
投票
" I love 1000 and 100 dollars.".split().count('100')

仅供参考,以下是计算每个单词的方便有效的方法。

from collections import Counter

Counter("I love 1000 and 100 dollars.".split())

# result: Counter({'I': 1, 'love': 1, '1000': 1, 'and': 1, '100': 1, 'dollars.': 1})
© www.soinside.com 2019 - 2024. All rights reserved.