【发布时间】:2016-03-31 13:50:10
【问题描述】:
在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
【问题讨论】:
-
我使用 Python 2.7.6 使用
re.compile("|".join(word_list * 1000000))尝试了您的列表一百万次,但没有收到此类错误。问题可能出在你的 word_list 中,每个单词都需要re.escape。 -
感谢您的关注。我使用 .split() 函数来创建我的单词列表。如果可能,请提供有关
re.escape的更多详细信息。 -
这个明显是由列表大小引起的错误,实际上可能是由4000个单词列表中包含无效正则表达式的单词引起的。因此,每个单词都应该像这样转义:
words_re = re.compile("|".join([re.escape(word) for word in word_list])) -
@cr3 我们的评论代码有效。请将其发布为答案,并请比较基于正则表达式的解决方案(您的答案)和 Malik Brahimi 的答案。谢谢
标签: python regex string list python-2.7