【问题标题】:check matches and match type for strings with multiple words against array of words针对单词数组检查具有多个单词的字符串的匹配项和匹配类型
【发布时间】:2022-12-24 22:47:26
【问题描述】:

我有一个固定的单词数组,我有一组字符串,我想检查它是否包含与单词数组的匹配项。 我还想确定四种可能的匹配类型:

  • 单字,完全匹配
  • 多个单词,其中一个完全匹配
  • 单个词,部分匹配
  • 多个词,部分匹配

我有前 3 个的支票,但正在努力获得第 4 个类型。还想知道这是否可以做得更好/更 pythonic/更有效。

a = ['1234','tes','1234 abc','tes abc']
b = ['1234','testing12','test']

def match_string(a, b):
    if [a for x in b if a.lower() == x.lower()]:
        match_type = 'exact - single'
    elif [a for x in b if a.lower() in x.lower()]:
        match_type = 'partial - single'
    elif [a for x in b if x.lower() in a.lower()]:
        match_type = 'exact - multiple'
    #add check for 4th type; 'partial - multiple'
    else:
        match_type = 'no match'
        
    return match_type

for string in a:
    print(match_string(string, b))

所需的输出是“精确 - 单一”、“部分 - 单一”、“精确 - 多重”、“部分 - 多重”

【问题讨论】:

  • [("partial - multiple" if len(w) > 1 else "partial - single") if (w := set(i.split())).intersection(x := [k for j in w for k in b if j in k]) else ("exact - multiple" if len(w) > 1 else "exact - single") if x else "no match" for i in a]
  • 这给了我错误的例子结果
  • 是的,我的错,只需切换 "partial""exact" 或反转条件。 Tio

标签: python


【解决方案1】:

您不需要为每个条件初始化循环。首先将第一个字符串拆分为 (str.split()).然后遍历并检查你的静态词表包含单词.如果不迭代恒定的单词列表并检查是否有不变的词包含单词.

def match_string(x, y):
    w = x.split()
    for i in w:
        if i in y:
            if len(w) > 1:
                return "exact - multiple"
            else:
                return "exact - single"
        else:
            for j in y:
                if i in j:
                    if len(w) > 1:
                        return "partial - multiple"
                    else:
                        return "partial - single"
    return "no match"

用法:

a = "1234", "tes", "1234 abc", "tes abc", "dfdfd"
b = "1234", "testing12", "test"

for s in a:
    print(s, "|", match_string(s, b))

输出:

1234 | exact - single
tes | partial - single
1234 abc | exact - multiple
tes abc | partial - multiple
dfdfd | no match

【讨论】:

  • changed if j.startswith(i): 因此部分匹配仅在字符串是匹配词的开头时才有效。
猜你喜欢
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2021-10-04
  • 2014-03-04
相关资源
最近更新 更多