Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python if multiple string return the words that contains in the sentences

I have a list of words and I want to do if statement, below is my list:

list = ['camera','display','price','memory'(will have 200+ words in the list)]

Here is my code:

def check_it(sentences):
    if 'camera' in sentences and 'display' in sentences and 'price' in sentences:
        return "Camera/Display/Price"
    if 'camera' in sentences and 'display' in sentences:
        return "Camera/Display"
    ...
    return "Others"

h.loc[:, 'Category'] = h.Mention.apply(check_it)

There will be too many combinations for these and also I want to have the words return to row individually. Does anyone know how to make this sample and return the word individually instead of doing 'camera/display/price'?

like image 462
Aimee Avatar asked Apr 11 '26 12:04

Aimee


1 Answers

Use str.findall by regex - join all values of lists with |, last str.join values by /:

df = pd.DataFrame({'Mention':['camera in sentences and display in sentences',
                              'camera in sentences price']})


L = ['camera','display','price','memory']
pat = '|'.join(r"\b{}\b".format(x) for x in L)
df['Category'] = df['Mention'].str.findall(pat).str.join('/')
print (df)
                                        Mention        Category
0  camera in sentences and display in sentences  camera/display
1                     camera in sentences price    camera/price

Another solution with list comprehension, also for list use generator with join:

df['Category1'] = [[y for y in x.split() if y in L] for x in df['Mention']]
df['Category2'] = ['/'.join(y for y in x.split() if y in L) for x in df['Mention']]
print (df)
                                        Mention          Category1  \
0  camera in sentences and display in sentences  [camera, display]   
1                     camera in sentences price    [camera, price]   

        Category2  
0  camera/display  
1    camera/price  
like image 134
jezrael Avatar answered Apr 14 '26 00:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!