【发布时间】:2019-06-26 03:08:38
【问题描述】:
我正在使用 Python,我想将给定的字符串与多个子字符串匹配。我试图以两种不同的方式解决这个问题。我的第一个解决方案是将子字符串与以下字符串匹配:
str = "This is a test string from which I want to match multiple substrings"
value = ["test", "match", "multiple", "ring"]
temp = []
temp.extend([x.upper() for x in value if x.lower() in str.lower()])
print(temp)
导致 temp = ["TEST", "MATCH", "MULTIPLE", "RING"]
但是,这不是我想要的结果。子字符串应该完全匹配,所以“ring”不应该与“string”匹配。
这就是我尝试用正则表达式解决这个问题的原因,如下所示:
str = "This is a test string from which I want to match multiple substrings"
value = ["test", "match", "multiple", "ring"]
temp = []
temp.extend([x.upper() for x in value if regex.search(r"\b" + regex.escape(x) + r"\b", str,
regex.IGNORECASE) is not None])
print(temp)
这导致 ["TEST", "MATCH", "MULTIPLE"] 正确的解决方案。尽管如此,这个解决方案的计算时间太长了。我必须对大约 100 万个字符串进行此检查,与使用第一个解决方案需要 1.5 小时相比,使用正则表达式的解决方案需要几天时间才能完成。
我想知道是否有办法让第一个解决方案运行起来,或者让第二个解决方案运行得更快。提前致谢
编辑:value 也可以包含数字,或者像“test1 test2”这样的短语
【问题讨论】:
-
您可以通过编译解决方案并在数百万个字符串上运行编译版本来节省大量时间
-
@jeremycg “编译你的解决方案”到底是什么意思?
-
but this does not work when value contains substrings like "test1 test2"。那么如果 value 有一个单词包含在str中,那么会有匹配项吗? -
使用@Kevin 在他的回答中提到的
re.compile
标签: python regex python-3.x string substring