我正在尝试使用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'
但我总是收到错误“无法散列的类型:”列表”。我尝试将列表转换为数组,但是错误仅显示“不可散列类型:'列表”。我将不胜感激!
答案 0 :(得分: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]