我需要檢查一個字符串是否包含列表的任何元素。我目前使用這種方法:Python - 檢查字符串是否包含列表中的任何元素
engWords = ["the", "a", "and", "of", "be", "that", "have", "it", "for", "not"]
engSentence = "the dogs fur is black and white"
print("the english sentence is: " + engSentence)
engWords2 = []
isEnglish = 0
for w in engWords:
if w in engSentence:
isEnglish = 1
engWords2.append(w)
if isEnglish == 1:
print("The sentence is english and contains the words: ")
print(engWords2)
這裏的問題是,它給輸出:
the english sentence is: the dogs fur is black and white
The sentence is english and contains the words:
['the', 'a', 'and', 'it']
>>>
正如你可以看到「a」和「它」不應該存在。我如何搜索,以便它只會列出單個單詞,而不是單詞的一部分?我願意使用普通的Python代碼或正則表達式(儘管我對Python和正則表達式都很新,所以請不要太複雜)謝謝。
這裏沒有任何正則表達式 - 這只是字符串操作。正則表達式是一種針對字符串提供匹配模式的非常具體的方式,如果您正在使用它們,您將使用're'模塊。 – geoelectric 2015-04-03 20:38:34
順便說一句,值得注意的是,所有這些解決方案(包括我的)只有在沒有標點符號時纔有效。任何標點符號都將看起來像它旁邊的單詞的一部分,並使您的比較失敗。 如果你開始包括標點符號,你需要一些策略來刪除或忽略它。一種策略是針對整個句子字符串使用正則表達式,在每個單詞的任一側使用'\ b'來搜索。 – geoelectric 2015-04-03 20:51:10