【问题标题】:Python - Check if two words are in a stringPython - 检查两个单词是否在字符串中
【发布时间】:2016-10-17 14:05:20
【问题描述】:

我想检查两个词“汽车”和“摩托车”是否在 Python 中数组的每个元素中。我知道如何用in 检查一个词,但不知道如何处理两个词。非常感谢任何帮助

【问题讨论】:

  • 使用逻辑与运算符:if cond1 and cond2:
  • 只需使用and 运算符

标签: python


【解决方案1】:

二字解法:

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

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

【讨论】:

  • all(map(lambda w: w in text, ('car', 'motorbike'))) 干净多了...
  • 嗯,在某种程度上你是对的。但是,这取决于您所说的干净是什么意思。当您浏览我的代码的每一行时,很明显发生了什么,而在您的代码中,我可能理解正在发生的事情,您也可能理解,但初学者可能无法理解。我的回答是以初学者应该能够理解正在发生的事情而不是作为一个要复制粘贴的单行者的方式编写的。但是,您的解决方案占用的空间更少,甚至可能更快,您是对的!
  • if 'car' in string and 'motorbike' in string.split(): 为什么不在这两种情况下拆分?
【解决方案2】:

使用辅助布尔值。

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。

【讨论】:

  • 使用print表示是否匹配
【解决方案3】:

我认为一个简单的解决方案是这样的:

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

现在它可以工作了!

【讨论】:

  • 不需要将参数中的set转换为issubset,该方法采用iterable:set(words).issubset(text.split())
【解决方案4】:

我会使用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)

【讨论】:

    【解决方案5】:

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


    我认为没有一种简单且 Pythonic 的方法可以做到这一点。您需要使用如下丑陋的逻辑:

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

    但是最后这 2 段代码在 python 中还不能工作。

    【讨论】:

    • 我刚刚测试过,发现这行得通:if value1 in string and value2 in string.只需要两个 in 语句
    【解决方案6】:

    使用此功能可以检查句子中带有“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')   
    

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 2021-04-04
      • 2019-11-07
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多