在Python中将多个字符串的列表连接回单个字符串的列表时出现问题

2024-04-20 11:17:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个Python程序来检查文件中的短语是否出现在文档中。我的程序运行良好,直到它遇到一个短语,如“快乐(+)脚”。我认为这个错误与短语中的“(+)”有关;但是,我不知道如何修改我的正则表达式使其工作。你知道吗

这是我的密码:

import re
handle = open('document.txt', 'r')
text = handle.read()

lst = list()
with open('phrases.txt', 'r') as phrases:
    for phrase in phrases:
        phrase = phrase.rstrip()
        if len(phrase) > 0 and phrase not in lst:
            ealst.append(phrase)

counts = {}
for each_phrase in lst:
    word = each_phrase.rsplit()
    pattern = re.compile(r'%s' % '\s+'.join(word), re.IGNORECASE)
    counts[each_phrase] = len(pattern.findall(text))

for key, value in counts.items():
    if value > 0:
       print key,',', value

 handle.close()
 phrases.close()

Tags: textinretxtforlenifvalue
1条回答
网友
1楼 · 发布于 2024-04-20 11:17:27

声明word时需要使用^{}

word = map(re.escape, each_phrase.rsplit())

也许,将\s+更改为\s*,以使空格成为可选的:

pattern = re.compile(r'%s' % '\s*'.join(word), re.IGNORECASE)

圆括号()以及+加符号special regex characters必须在字符类之外的正则表达式中转义,以匹配文字字符。你知道吗

样本IDEONE demo

相关问题 更多 >