[英]Python regex special characters with inputed search strings
在这里一些最优秀的成员的帮助下,我已经学到了很多有关正则表达式的知识,并且半熟练了。 我需要在正则表达式搜索中添加以下字符:“,():;-。?。问题是我正在将输入的搜索字符串传递给正则表达式,并且不知道如何使它起作用。
这是代码:
text = open_file.read()
grammarList = raw_input("Enter your grammar string: ");
tags = grammarList.split("^")
tags_pattern = r"\b" + r"\s+".join(r"(\w+)/{0}".format(tag) for tag in tags) + r"\b"
# gives you r"\b(\w+)/NNP\s+(\w+)/CC\s+(\w+)/NNP\b"
from re import findall
start_position = 0
for poem in poemList:
start_position = text.find('<' + poem + '>', start_position)
end_position = text.find('</' + poem + '>', start_position)
searchtext = text [start_position:end_position]
poemname = poem
for oldname, newname in poemtitleswapList.items():
poemname = poemname.replace(oldname, newname)
print poemname
print(findall(tags_pattern, searchtext))
print "\n"
这是文本文件的示例:
To/TO
emotion/NN
for/IN
all/DT
there/EX
is/VBZ
in/IN
it/PRP
,/,
它适用于除逗号,圆括号,句号,分号,问号,冒号,破折号和引号之外的所有内容。 我也需要它才能找到这些东西。 任何帮助将非常感激。
您可以使用re.escape(tag)
对正则表达式中具有特殊含义的字符进行re.escape(tag)
。 要允许左侧的非单词字符,您可以将\\w+/
替换为[^/]+/
:
pattern = r'\s+'.join(r"^([^/]+)/{0}".format(re.escape(tag)) for tag in tags)
print re.findall(pattern, searchtext, re.M)
[('is', 'in', 'it', ',')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.