【问题标题】:best way count the number of matches between the list and the string in python最好的方法计算列表和python中字符串之间的匹配数
【发布时间】: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


【解决方案1】:

如果您希望不区分大小写并匹配忽略标点符号的整个单词,请拆分字符串并使用 dict 去除标点符号以存储您要计算的单词:

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}

如果您只想求和,请使用具有相同逻辑的 set

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 效率更高。

【讨论】:

    猜你喜欢
    • 2014-06-28
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2020-02-19
    • 2021-02-15
    相关资源
    最近更新 更多