Here is a simple dataset:
import pandas as pd
product = ['knife', 'box set', 'beautiful jewellery set on sale', 'green']
df = pd.DataFrame(product, columns = ['product_name'])
df
The output as follows:
| product_name | |
|---|---|
| 0 | knife |
| 1 | box set |
| 2 | beautiful jewellery set on sale |
| 3 | green |
I want to categorise these products by extracting two consecutive nouns if needed. So far I have the following, but the categories are presented by only one noun for all cases:
!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
The output I have:
| product_category | |
|---|---|
| 0 | knife |
| 1 | set |
| 2 | jewellery |
| 3 | NaN |
The expected output:
| product_category | |
|---|---|
| 0 | knife |
| 1 | box set |
| 2 | jewellery set |
| 3 | NaN |
Is it possible to introduce some additional conditions to the code to extract two nouns if they follow one after another?