如何在 pandas 中查找单词?还是两个词的组合?

How to find words in pandas? Or the combination of two words?

我需要从文本中找到两个词的组合,还要列出下一个词。例如,我有这样的 df:

id                 date                     text
1                  1.1.20                   this is a sweet cat.
2                  1.1.20                   the cat is sweet.
3                  2.1.20                   sweet dogs are difficult to find.
4                  3.1.20                   I love sweet cats.

首先我需要找到两个词的组合...例如"sweet cat"

我想我可以使用 str.contains 来完成,但它不能正常工作...它缺少很多行。

我想搜索单词的第二件事是生成搜索单词列表,旁边是单词。

例如我搜索 df[df['text'].str.contains('sweet')] 然后它应该像这样生成列表:

list
['sweet cat', 'sweet', 'sweet dogs', 'sweet cats']

您可以使用 df.str.split:

d = df[df['text'].str.contains('sweet')]

d.text.apply(lambda x: 'sweet ' + x.split('sweet')[-1].split()[0].strip('.')).tolist()

输出:

['sweet cat', 'sweet ', 'sweet dogs', 'sweet cats']

另一个解决方案,使用 re 模块:

import re
import pandas as pd

df = pd.DataFrame({'sentences': ['this is a sweet cat.', 'the cat is sweet.', 'sweet dogs are difficult to find.', 'I love sweet cats.']})

kw = 'sweet'
r = re.compile(r'\b({})\s*(\w*)'.format(re.escape(kw)))

print( df['sentences'].apply(lambda x: [' '.join(t).strip() for t in r.findall(x)]).explode().tolist() )

打印:

['sweet cat', 'sweet', 'sweet dogs', 'sweet cats']

您可以使用pd.Series.str.extract

df['text'].str.extract('(sweet\s*\w*|sweet)', expand=False).tolist()
# ['sweet cat', 'sweet', 'sweet dogs', 'sweet cats']