在python中,句子正好包含这个词

2024-09-29 19:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想返回包含搜索列表中确切单词的句子

df = pd.read_excel('C:/Test 1012/UOI.xlsx')
a = df['Content']
searchfor =['hot' ,'yes'  and 200 more words in it]
b = a[a.str.contains('|'.join(searchfor))]
print(b)

例如:

Content = ['the photo is good','nice picture'...]

结果不应该打印任何句子,但是,'照片'包含'热'字,结果给我'照片是好的'。有人知道怎么解决这个问题吗?我只想得到的结果完全包含搜索列表中的单词


Tags: testdf列表readcontentxlsx单词excel
1条回答
网友
1楼 · 发布于 2024-09-29 19:35:49

使用为searchfor的每个值添加的单词边界:

df = pd.DataFrame({'Content':['the photo is good','nice picture']})
print (df)
             Content
0  the photo is good
1       nice picture

searchfor =['hot','yes','nice']
pat = '|'.join(r"\b{}\b".format(x) for x in searchfor)


b = df.loc[df['Content'].str.contains(pat), 'Content']
#your solution
#b = a[a.str.contains(pat)]
print (b)
1    nice picture
Name: Content, dtype: object

相关问题 更多 >

    热门问题