2016-10-17 81 views
0

我想檢查Python中數組的每個元素中是否有兩個單詞「car」和「motorbike」。我知道如何檢查一個詞與in,但不知道如何處理2個單詞。非常感謝所有幫助Python - 檢查兩個單詞是否在字符串中

+3

使用邏輯與運算符:'如果cond1和cond2:' – Li357

+0

只需使用'和'運算符 –

回答

4

兩個詞解:

for string in array: 
    if 'car' in string and 'motorbike' in string.split(): 
     print("Car and motorbike are in string") 

字頭的解決方案,以檢查是否所有單詞test_wordsstring

test_words = ['car', 'motorbike'] 
contains_all = True 

for string in array: 
    for test_word in test_words: 
     if test_word not in string.split():: 
      contains_all = False 
      break 
    if not contains_all: 
     break 

if contains_all: 
    print("All words in each string") 
else: 
    print("Not all words in each string") 
+1

'all(map(la mbda w:w在文本中,('car','motorbike')))'更清潔... – ldavid

+4

好吧,在某種程度上,你是對的。但是,這取決於您的清潔意味着什麼。當你閱讀我的代碼的每一行時,很明顯發生了什麼,而在你的行中,我可能會理解正在發生的事情,你也是如此,但初學者可能不瞭解它。我的回答是以一種初學者應該能夠理解正在發生的事情的方式編寫的,而不是作爲複製粘貼的複製內容。但是,您的解決方案佔用的空間相對較少,甚至可能更快,您說得對! –

1

使用附配布爾值。

car=False 
motorbike=False 
for elem in array: 

     if "car" in elem: 
      car=True 
     if "motorbike" in elem: 
      motorbike=True 
     if car and motorbike: 
      break 

編輯:我只是讀「在每個元素」。只需使用AND。

+0

使用'print'來指示是否匹配 – user2728397

0

我認爲一個簡單的解決辦法是這樣的:

all(map(lambda w: w in text, ('car', 'motorbike'))) 

但有可能是這個問題,這取決於你如何挑剔需要的比較是:

>>> text = 'Can we buy motorbikes in carshops?' 
>>> all(map(lambda w: w in text, ('car', 'motorbike'))) 
True 

寫着「車'和'摩托車'不在text,這仍然說True。你可能需要完全匹配的文字。我會這樣做:

>>> words = ('car', 'motorbike') 
>>> text = 'Can we buy motorbikes in carshops?' 
>>> set(words).issubset(text.split()) 
False 
>>> text = 'a car and a motorbike' 
>>> set(words).issubset(text.split()) 
True 

現在它的工作!如果我們有一個字符串列表

wanted_values = ("car", "motorbike") 
all(vehicle in text for text in wanted_values) 

所以:

l = ['some car and motorbike', 
    'a motorbike by a car', 
    'the car was followed by a motorbike'] 

lines_with_vehicles = [text for text in l 
         if all(vehicle in text for text in wanted_values)] 

用正則表達式,你可以這樣做:

+2

該參數不需要'set'轉換到'issubset',該方法需要一個可迭代的:'set(words).issubset(text.split())' –

0

我會用all功能

# no particular order 
car_and_motorbike_pattern = re.compile(r'(car.*motorbike|motorbike.*car)') 
all(car_and_motorbike_pattern.search(text) for text in list_of_expressions) 

# This works too 
car_or_motorbike_pattern = re.compile(r'(car|motorbike)') 
get_vehicles = car_or_motorbike_pattern.findall 
all(len(set(get_vehicles(text))) == 2 for text in list_of_expressions) 
相關問題