【发布时间】: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