[英]check matches and match type for strings with multiple words against array of words
我有一個固定的單詞數組,我有一組字符串,我想檢查它是否包含與單詞數組的匹配項。 我還想確定四種可能的匹配類型:
我有前 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))
所需的 output 是“精確 - 單一”、“部分 - 單一”、“精確 - 多個”、“部分 - 多個”
您不需要為每個條件初始化循環。 首先將第一個字符串拆分為單詞(str.split()
) 。 然后遍歷words並檢查您的static 單詞列表是否包含word 。 如果不迭代單詞的常量列表並檢查是否有任何常量單詞包含word 。
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))
Output:
1234 | exact - single
tes | partial - single
1234 abc | exact - multiple
tes abc | partial - multiple
dfdfd | no match
你可以幫助我的國家,查看我的個人資料信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.