【发布时间】: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。