python - 如何识别包含多个单词的字符串

标签 python regex conditional-statements string-search

数据类型为字符串的数据框列文本包含句子,我希望提取包含某些单词的行,无论它们出现的位置如何。

例如:

Column
Cat and mouse are the born enemies
Cat is a furry pet


df = df[df['cleantext'].str.contains('cat' & 'mouse')].reset_index()
df.shape

上面抛出了一个错误。

我知道对于或条件我们可以写 -

df = df[df['cleantext'].str.contains('cat | mouse')].reset_index()

但是我想提取猫和老鼠都存在的行

预期输出 -

Column
Cat and mouse are the born enemies

最佳答案

这是一种方法,也适用于多个单词:

words = ['cat', 'mouse']
m = pd.concat([df.Column.str.lower().str.contains(w) for w in words], axis=1).all(1)
df.loc[m,:]

      Column
0  Cat and mouse are the born enemies

关于python - 如何识别包含多个单词的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56008377/

相关文章:

python - Tensorflow v1.14 中的梯度裁剪错误

Python - 如何通过空格将标点符号与单词分开,在标点符号和单词之间只留下一个空格?

javascript - 基于条件的不同ng类?

Flutter/Dart - 将逗号分隔的字符串拆分为 3 个变量?

python - 如何根据子列表中的条件删除列表元素

python - Windows 上的 RabbitMQ 可移植?

python - 在python中使用ElementTree删除特定的xml标签

python - 预期类型 'List[A]'(匹配泛型类型 'List[_T]' ),在正确键入的列表中得到 'List[B]'

javascript - 正则表达式在捕获组中保留尾随斜杠

c# - 匹配 M/YYYY、MM/YYYY、M/YY 或 MM/YY 格式的正则表达式