這個問題在這里已經有了答案: 如何檢查字串是否包含 Python 中串列中的元素 7 個答案 3天前關閉。
我有一個清單如下:
item_list=['Manpower Service','Manpower Outsourcing','Healthcare Sanitation','Hiring
of Sanitation','Custom Bid For Services','Sanitation',
'Facility Management', 'Security Manpower Service']
并有一個像這樣的字串:
String_text="Manpower Outsourcing Services - Minimum Wage - Sem..."
這個字串每次都會改變。我想要檢查是否有任何串列項包含在字串中并且我不知道該怎么做?有人可以建議我一個好方法嗎?
uj5u.com熱心網友回復:
請注意,這也可能是 NLP 問題,但我的解決方案不是。
如果您打算檢查串列中的成員是否在字串中,那應該很簡單。
[i for i in item_list if i in String_text]
... ['Manpower Outsourcing']
這將只保留字串中的串列成員,但請注意它只會保留“完全匹配”。
如果此輸出不適合您的目的,可能還有其他幾種方法可以檢查。
字串中的成員標記為 1,其他成員標記為 0。
[1 if i in String_text else 0 for i in item_list]
... [0, 1, 0, 0, 0, 0, 0, 0]
或者,如果您想檢查字串中每個成員的數量,我建議將它們拆分。
item_list2 = [i.split(" ") for i in item_list]
[sum([1 if i in String_text else 0 for i in x])/len(x) for x in item_list2]
... [1.0, 1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.6666666666666666]
您會注意到最后一個與前者的輸出不同,因為第一個成員“Manpower Service”在字串中分別作為“Manpower”和“Service”出現。您可以根據自己的目的選擇合適的解決方案。
再次請注意,這可能是一個 NLP 問題,我的解決方案只是愚蠢的字串匹配。
uj5u.com熱心網友回復:
我對“這個字串每次都會改變”感到很困惑,但我希望下面的代碼可以解決你的問題。
[x for x in item_list if x in String_text]
uj5u.com熱心網友回復:
最簡單的方法是遍歷 in 的值item_list并使用in關鍵字檢查每個專案是否在String_text字串中:
found = False
found_item = ""
for item in item_list:
found = item in String_text
if found:
found_item = item
break
print("Was item found: " str(found))
if found:
print("Item Found: " found_item)
uj5u.com熱心網友回復:
這是您可以添加的示例。您可以嘗試執行 for range 回圈(如下所示)。使用 if 陳述句和“in”引數,它將檢查串列當前索引中的至少部分字串是否與字串匹配。
for i in range(0, len(item_list)):
# If the current list item matches the string, then it will print
# out what item in the list it matches with 'String_text'.
if item_list[i] in String_text:
print(f"'{item_list[i]}' in String_text")
注意:它不必是“i”,它可以是任何你想要的未使用的變數(例如“item”、“index”等)。我只是在這個例子中使用了“i”。另請注意,匹配字串是區分大小寫的。
我運行了代碼,這是我得到的輸出:
'Manpower Outsourcing' in String_text
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433697.html
上一篇:在TCL中,如何洗掉字串中的子字串,并且還必須為檔案中的不同字串執行此操作
下一篇:洗掉除數字以外的重復單詞
