【问题标题】:find list of strings in list of strings, return boolean在字符串列表中查找字符串列表,返回布尔值
【发布时间】:2019-03-31 16:49:17
【问题描述】:

我正在尝试使用 python 中的字符串列表,但不知何故我找不到一个好的解决方案。我想在字符串列表中查找字符串列表并返回布尔值:

import re
sentences = ['Hello, how are you?',
             'I am fine, how are you?',
             'I am fine too, thanks']
bits = ['hello', 'thanks']

re.findall(sentences, bits)

# desired output: [True, False, True]

因此,如果句子字符串包含一个或多个位,我想获得一个带有 True 的布尔数组。我也试过了

bits = r'hello|thanks'

但我总是收到错误“不可散列的类型:'list'”。我尝试将列表转换为数组,但错误只是说'unhashable type:'list''。如果有任何帮助,我将不胜感激!

【问题讨论】:

  • 您的示例都是纯字母文本,没有实际的正则表达式,因此您可以使用if word in sentence:
  • 对于涉及检查匹配开始/结束/包含特殊字符的整个单词的通用场景的正则表达式解决方案,请参阅this demo

标签: python regex


【解决方案1】:

一种选择是使用嵌套列表推导:

sentences = ['Hello, how are you?',
             'I am fine, how are you?',
             'I am fine too, thanks']
bits = ['hello', 'thanks']

[any(b in s.lower() for b in bits) for s in sentences]
# returns:
[True, False, True]

如果要使用正则表达式,需要用竖线字符连接bits,但仍需要单独检查sentences 中的每个句子。

[bool(re.search('|'.join(bits), s, re.IGNORECASE)) for s in sentences]
# returns:
[True, False, True]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2012-05-16
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多