【问题标题】:How to search a text string and know if there's a certain word?如何搜索文本字符串并知道是否有某个单词?
【发布时间】:2021-10-27 15:02:44
【问题描述】:

我编写了一个搜索文本并找到某个单词的函数,但它说没有那个单词 - 但我知道有,所以它不起作用。

def search(text, item):
    list_ = []
    p = [';', '.', ' ', ',', ':']
    string = ''
    for i in range(len(text)):
        if text[i] not in p:
            string += text[i]
        else:
            list_ += string
            string = ''
    if item in list_:
        return True
    else:
        return False

【问题讨论】:

  • 请分享您提供的输入'
  • 变量n是什么?应该是list.append(string)
  • 仅供参考:您应该改掉使用for i in range(len(...)) 的习惯,改用for item in ...
  • 如果你想用多个分隔符分割一个字符串,考虑使用re.split()而不是这样的循环。
  • Protip:不要使用list作为变量名,因为它会影响内置的list类型。

标签: python string


【解决方案1】:

这里有一些确实有效的东西。它使用正则表达式来确定文本中的“单词”是什么,我认为这是问题的症结所在。它将它们全部放在set 中,然后使用in 运算符确定传递的item 是否是其中的成员。

import re


WORD_PATTERN = re.compile("([\w][\w']*\w)")  # Regex to find words in a string.
                                             # see https://stackoverflow.com/a/12705513/355230

def search(text, item):
    words = {*WORD_PATTERN.findall(text)}  # Set for fast membership testing.
    return item in words


if __name__ == '__main__':

    s = "John's mom went there, but he wasn't there. So she said: 'Where are you?'"

    for word in ('mom', 'bug', 'so', 'So', "wasn't"):
        print(f'{word!r} in string s -> {search(s, word)}')

打印输出:

'mom' in string s -> True
'bug' in string s -> False
'so' in string s -> False
'So' in string s -> True
"wasn't" in string s -> True

如您所见,搜索区分大小写。另请注意,在处理撇号方面存在一些微妙之处 - 请参阅answer 了解详细信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多