我在一个.txt文件中有一长串单词和regular expression patterns,我这样读:
with open(fileName, "r") as f1:
pattern_list = f1.read().split('\n')
为了举例说明,前七个是这样的:
^{pr2}$我想知道何时将输入字符串中的单词与pattern\u列表中的任何单词/模式匹配。下面的在某种程度上是有效的,但我看到两个问题:
if w in regex_compile_list:
的功能,它不能正常工作。)我做错了什么?我怎样才能更有效率?提前感谢你对一个无赖的耐心,并感谢你的任何洞察力!在
string_input = "People who have been abandoned or abused will often be afraid of adversarial, abusive, or aggressive behavior. They are aching to abandon the abuse and aggression."
for raw_str in pattern_list:
pat = re.compile(raw_str)
for w in string_input.split():
if pat.match(w):
print "matched:", raw_str, "with:", w
#matched: abandon* with: abandoned
#matched: abandon* with: abandon
#matched: abuse* with: abused
#matched: abuse* with: abusive,
#matched: abuse* with: abuse
#matched: abusi* with: abused
#matched: abusi* with: abusive,
#matched: abusi* with: abuse
#matched: ache* with: aching
#matched: aching with: aching
#matched: advers* with: adversarial,
#matched: afraid with: afraid
#matched: aggress* with: aggressive
#matched: aggress* with: aggression.
为了匹配shell样式的通配符,您可以(ab)使用模块^{}
由于
fnmatch
主要是为文件名比较而设计的,因此测试将区分大小写,或者不取决于您的操作系统。所以您必须规范化文本和模式(这里,我使用lower()
来实现这个目的)制作:
^{pr2}$abandon*
将匹配abandonnnnnnnnnnnnnnnnnnnnnnn
,而不是{相反。在
如果
*
都在字符串的末尾,您可能需要执行类似以下操作:相关问题 更多 >
编程相关推荐