python - 最好的方法是计算 python 中列表和字符串之间的匹配次数

标签 python regex string list python-2.7

在 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/

相关文章:

C++ 将未终止的 char* 连接到 std::string

python - 计算字典中 get 方法返回第二个选项的次数

python - 如何使用逐元素操作获取多个 numpy 保存数组的均值和标准差

javascript - 需要你帮助一个简单的 javascript 正则表达式

java - 删除句子和段落之间的各种额外空格

mysql - SQL 查询到 STRING$

python - run_gunicorn 有效但 gunicorn_django 无效,尽管两者都在同一环境中,看不到注册模块

python - 如何在 Django 中使用 BeautifulSoup?

javascript - 正则表达式仅匹配较大字符串中引号中的新行

ruby 正则表达式 : match any . css 文件名不以下划线开头,在任何字符串之前