【问题标题】:Check if a sentence contains multiple words in a row (Python)检查一个句子是否连续包含多个单词(Python)
【发布时间】:2021-02-18 22:46:14
【问题描述】:

我想编写一个函数来检查给定的句子是否包含给定的单词。例如:

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

此示例将返回 True。现在,一旦字符串不仅仅是一个单词,就会出现问题。

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

这里它会返回 False。这个问题有简单的解决方案吗?

【问题讨论】:

    标签: python contains word sentence


    【解决方案1】:

    您可以使用正则表达式 - 您正在寻找的东西被单词边界封装:

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

    【讨论】:

    • 感谢您的回答,效果很好!我经常尝试避免使用正则表达式,因为它通常很慢(afaik,我无法让它更快)所以你知道是否有办法让这行代码更快地工作,或者可能只是另一个没有的解决方案是吗?
    • 确实,与其他可能的解决方案相比,正则表达式会相对慢。尽管我想知道,对于您的用例来说,正则表达式实际上是否“太慢”?如果您的实际用例并不比这复杂得多,并且不需要疯狂的模式,我不会担心做任何过早的优化。目前,我想不出任何其他不涉及正则表达式的可爱解决方案。
    • 这里的函数实际上只是一个大项目中的一小部分,不幸的是涉及到大量的单词和句子
    【解决方案2】:

    试试

    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
    

    这应该适用于您的问题和您的各种要求。

    原文:

    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
    

    【讨论】:

    • 您好,感谢您的回答!您的解决方案肯定解决了我的示例中的问题,但如果有类似的内容:my_string = 'Unite' sentence = 'Joe Biden is the new President of the United States.'它仍然会返回 True,我不希望我的函数这样做。
    • 嗯,还有一个很长的解决方案,我会在里面编辑它...
    • 谢谢,问题解决了!但是现在我的用例还有另一个问题:如果有一个像“拜登总统”这样的字符串,它会返回 True,但我只希望一个字符串在给定句子中以完全相同的顺序出现时返回 True。
    【解决方案3】:

    试试看:

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

    【讨论】:

    • 根据用例,这可能不是最佳解决方案。例如,如果您在字符串“By pass it over..”中搜索“bypass”,您的代码将改为在字符串“bypassingitover...”中搜索“bypass”并解析为 true。
    • @Befeepilf 我同意。谢谢。我更新了我的建议。
    • 不幸的是,这个解决方案会在我不想要的像“Unite”这样的字符串上返回 True
    猜你喜欢
    • 2018-04-03
    • 2019-05-29
    • 2020-07-06
    • 2019-01-06
    • 2012-03-26
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2022-06-19
    相关资源
    最近更新 更多