gpt4 book ai didi

python如果多个字符串返回句子中包含的单词

转载 作者:行者123 更新时间:2023-11-28 20:58:13 26 4
gpt4 key购买 nike

我有一个单词列表,我想做 if 语句,下面是我的列表:

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

这是我的代码:

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)

这些组合太多了,我也想让单词单独返回行。有谁知道如何制作这个样本并单独返回单词而不是做“相机/显示器/价格”?

最佳答案

使用str.findall通过正则表达式 - 使用 | 加入列表的所有值,最后一个 str.join / 的值:

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

另一种列表理解的解决方案,也适用于带有 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

关于python如果多个字符串返回句子中包含的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51927650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com