【问题标题】:how to detect partial pattern in partial string in python [duplicate]如何在python中检测部分字符串中的部分模式[重复]
【发布时间】:2021-11-03 05:30:40
【问题描述】:
val = "one two three four five" 
string1 = "you id is one two three" 
string2 = "continue to four five"

Expect output: Start span and end span
output1 = 10,22 
output2 = 12,20

这里string1和string2中存在一些val的包含。我们需要检测spans

【问题讨论】:

  • 你查了吗Longest Common Substring,网上有很多解决办法

标签: python regex nlp re


【解决方案1】:

形成数字关键字的正则表达式交替,然后迭代以查找与其索引的所有匹配项:

val = "one two three four five"
string1 = "you id is one two three"
regex = r'\b(?:' + '|'.join(val.split()) + r')\b'
p = re.compile(regex + r'(?: ' + regex + r')*')

for m in p.finditer(string1):
    print(m.start(), m.end(), m.group())  # (10, 23, 'one two three')

这里要清楚,使用的正则表达式是这样的:

\b(?:one|two|three|four|five)\b(?: \b(?:one|two|three|four|five)\b)*

【讨论】:

  • 我不确定它是否重要,但它不会保留val 中出现的单词的优先级,例如string1 = "you id is two one three"
  • 非常感谢!!!!!
【解决方案2】:

您可以轻松地使用difflib,而不是使用re,因为它已经提供了您需要的确切功能,即find_longest_match()

import difflib

val = "one two three four five" 

for my_string in [
    "your id is one two three",
    "continue to four five six",
]:
    sequence_matcher = difflib.SequenceMatcher(a=val, b=my_string)
    match = sequence_matcher.find_longest_match(0, len(val), 0, len(my_string))
    match_str = my_string[match.b:match.b + match.size]
    print(match.b, match.b + match.size, match_str)

输出:

10 23 one two three
11 21  four five

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2014-06-14
    相关资源
    最近更新 更多