简体   繁体   English

检查一个句子是否连续包含多个单词(Python)

[英]Check if a sentence contains multiple words in a row (Python)

I want to write a function that checks if a given sentence contains given words.我想写一个 function 来检查给定的句子是否包含给定的单词。 For example:例如:

my_string = 'Biden'
sentence = 'Biden is the new president of the United States.'

if my_string.lower() in sentence.lower().split():
    print('Sentence contains string')
else:
    print('Sentence does not contain string')

This example would return True.此示例将返回 True。 Now a problem arises once the string isn't just a single word.现在,一旦字符串不仅仅是一个单词,就会出现问题。

my_string = 'Joe Biden'
sentence = 'Joe Biden is the new president of the United States.'

if my_string.lower() in sentence.lower().split():
    print('Sentence contains string')
else:
    print('Sentence does not contain string')

Here it would return False.在这里它将返回 False。 Is there simple solution for this problem?这个问题有简单的解决方案吗?

You could use a regular expression - the thing you're looking for encapsulated by word-boundaries:您可以使用正则表达式 - 您正在寻找由单词边界封装的东西:

import re

word = "Joe Biden"
pattern = f"\\b{word}\\b"

sentence = "Joe Biden is the new president of the United States"
match = re.search(pattern, sentence, re.IGNORECASE)

print(f"Sentence {('contains', 'does not contain')[match is None]} string")

Try尝试

my_string = 'Joe Biden'
sentence = 'Joe Biden is the new president of the United States.'
my_string = my_string.split()
sentence = sentence.split()
confirm = []
for i in sentence:
  if i in my_string:
    confirm.append(i)
if confirm == my_string:
  if sentence.find(my_string) != 0 - 1:
    # my_string is in sentence
    pass

This should work with your problem and your various requirements.这应该适用于您的问题和您的各种要求。

Original:原来的:

my_string = 'Joe Biden'
sentence = 'Joe Biden is the new president of the United States'
if sentence.find(my_string) != 0 - 1:
  # my_string is in sentence
  pass

Try that:试试看:

    my_string = 'Joe Biden'
sentence = 'Joe Biden is the new president of the United States.'

if my_string.lower() in sentence.lower(): 
    print('Sentence contains string')
else:
    print('Sentence does not contain string')

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

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