【发布时间】:2021-09-06 17:25:21
【问题描述】:
这是一个简单的数据集:
import pandas as pd
product = ['knife', 'box set', 'beautiful jewellery set on sale', 'green']
df = pd.DataFrame(product, columns = ['product_name'])
df
输出如下:
| product_name | |
|---|---|
| 0 | knife |
| 1 | box set |
| 2 | beautiful jewellery set on sale |
| 3 | green |
如果需要,我想通过提取两个连续的名词来对这些产品进行分类。到目前为止,我有以下内容,但在所有情况下,类别仅由一个名词表示:
!pip install -q --upgrade spacy
import spacy
nlp = spacy.load('en_core_web_sm')
category=[]
for i in df['product_name'].tolist():
doc = nlp(i)
for t in doc:
if t.pos_ in ['NOUN']:
category.append(f'{t}')
break
if t.pos_ not in ['NOUN']:
category.append('NaN')
df1 = pd.DataFrame(category, columns =['product_category'])
df1
我的输出:
| product_category | |
|---|---|
| 0 | knife |
| 1 | set |
| 2 | jewellery |
| 3 | NaN |
预期输出:
| product_category | |
|---|---|
| 0 | knife |
| 1 | box set |
| 2 | jewellery set |
| 3 | NaN |
如果两个名词一个接一个,是否可以在代码中引入一些附加条件来提取两个名词?
【问题讨论】:
-
将
matcher与相应的模式一起使用。 -
@WiktorStribiżew 非常感谢 Wiktor 的帮助。我会开始学习你展示的方法。
-
你能澄清一下你想要什么输出吗?我在上面的链接中显示的那个?
-
@WiktorStribiżew 我已经更新了问题并包含了预期的输出。