简体   繁体   English

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

[英]Python - Check if two words are in a string

I would like to check whether 2 words "car" and "motorbike" are in each element of an array in Python. I know how to check for one word with in but have no idea how to do with 2 words.我想检查 Python 数组的每个元素中是否包含“汽车”和“摩托车”这两个词。我知道如何用in检查一个词,但不知道如何处理两个词。 Really appreciate any help非常感谢任何帮助

Two word solution:两个字解决:

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

n-word solution to check if all words in test_words are in string :用于检查test_words中的所有单词test_words都在string n-word 解决方案:

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

Use an auxiliar boolean.使用辅助布尔值。

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

EDIT: I just read "in each element".编辑:我只是读了“在每个元素中”。 Just use AND.只需使用AND。

I think a simple solution is this:我认为一个简单的解决方案是这样的:

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

But there might be a problem with this, depending on how picky you need the comparison to be:但这可能存在问题,具体取决于您需要比较的挑剔程度:

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

The words 'car' and 'motorbike' are NOT in the text , and this still says True . text中没有“汽车”和“摩托车”这两个词,这仍然是True You might need a full match in words.您可能需要完全匹配单词。 I would do this:我会这样做:

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

And now it works!现在它起作用了!

I would use the all function:我会使用all功能:

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

So if we have a list of strings:所以如果我们有一个字符串列表:

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

With regex you could do:使用正则表达式,您可以:

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

This link worked for me: It offers 3 solutions. 此链接对我有用:它提供了 3 种解决方案。 Two methods use list comprehensions and the third one uses map + lambda functions.两种方法使用列表推导式,第三种使用 map + lambda 函数。


I think there is not an easy and pythonic way to do that.我认为没有一种简单的 Pythonic 方法可以做到这一点。 You need to use an ugly logic like the next:您需要使用如下丑陋的逻辑:

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

That would work for two words, but if you need to check many words, then better use the code in the link above这适用于两个词,但如果您需要检查很多词,那么最好使用上面链接中的代码


I would like to be able to do something like:我希望能够执行以下操作:

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

Or:或者:

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

But these 2 last pieces of code don't work in python (yet).但是这最后两段代码在 python 中不起作用(还)。

Use this function to check for two or more keywords in a sentence with 'and' or 'or' operators.使用此 function 来检查带有“and”或“or”运算符的句子中的两个或多个关键字。

def check_words(operator = 'and', words = ['car', 'bike'],
                sentence = 'I own a car but not a bike'):

    if operator == 'and':
        word_present = True
        for w in words:
            if w in sentence:
                word_present = True
            else:
                word_present = False
        return word_present

    elif operator == 'or':
        for w in words:
            if w in sentence:
                return True
            else:
                return False
        

check_words(operator = 'and', words = ['car', 'bike'],
            sentence = 'I own a car but not a bike')   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM