在 python 中计算列表和字符串之间匹配次数的最佳方法是什么?
例如,如果我有这个列表:
list = ['one', 'two', 'three']
和这个字符串:
line = "some one long. two phrase three and one again"
我想得到4因为我有
one 2 times
two 1 time
three 1 time
我根据 this question 尝试以下代码答案是有效的,但是如果我在列表中添加很多单词(4000 个单词),我会出错:
import re
word_list = ['one', 'two', 'three']
line = "some one long. two phrase three and one again"
words_re = re.compile("|".join(word_list))
print(len(words_re.findall(line)))
这是我的错误:
words_re = re.compile("|".join(word_list))
File "/usr/lib/python2.7/re.py", line 190, in compile
最佳答案
如果您想要不区分大小写并匹配忽略标点符号的整个单词,请拆分字符串并使用字典去除标点符号以存储您想要计算的单词:
lst = ['one', 'two', 'three']
from string import punctuation
cn = dict.fromkeys(lst, 0)
line = "some one long. two phrase three and one again"
for word in line.lower().split():
word = word.strip(punctuation)
if word in cn:
cn[word] += 1
print(cn)
{'three': 1, 'two': 1, 'one': 2}
如果您只想求和,请使用具有相同逻辑的集合:
from string import punctuation
st = {'one', 'two', 'three'}
line = "some one long. two phrase three and one again"
print(sum(word.strip(punctuation) in st for word in line.lower().split()))
这会在单词被拆分后对单词进行一次传递,集合查找为 0(1)
,因此它比 list.count
效率要高得多。
关于python - 最好的方法是计算 python 中列表和字符串之间的匹配次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464275/