Python - 检查字符串中是否有两个单词

时间:2016-10-17 14:05:21

标签: python

我想查看2个单词" car"和"摩托车"在Python中的数组的每个元素中。我知道如何用in检查一个单词,但不知道如何处理2个单词。非常感谢任何帮助

5 个答案:

答案 0 :(得分:6)

两个字的解决方案:

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

n字解决方案,用于检查test_words中的所有字词是否在string中:

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 :(得分: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。

答案 2 :(得分: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

现在它有效!

答案 3 :(得分:0)

我会使用all函数:

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)]

使用正则表达式,你可以做到:

# 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)

答案 4 :(得分:0)

This link为我工作: 它提供3个解决方案。两种方法使用列表推导,第三种方法使用map + lambda函数。


我认为没有简单而有效的方法可以做到这一点。您需要像下一个一样使用丑陋的逻辑:

image_file_name = 'man_in_car.jpg'
if 'car' in image_file_name and 'man' in image_file_name:
    print('"car" and "man" were found in the image_file_name')

这对两个单词有效,但是如果您需要检查很多单词,那么最好使用上面链接中的代码


我希望能够做类似的事情:

if 'car' and 'man' in image_file_name:
    print('"car" and "man" were found in the image_file_name')

或者:

if any(['car','man'] in image_file_name):
    print('"car" and "man" were found in the image_file_name')

但是最后两段代码在python中尚不可用。