我正在尝试编写一个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()
声明} :
word
时需要使用^{也许,将
\s+
更改为\s*
,以使空格成为可选的:圆括号
(
和)
以及+
加符号special regex characters必须在字符类之外的正则表达式中转义,以匹配文字字符。你知道吗样本IDEONE demo
相关问题 更多 >
编程相关推荐