gpt4 book ai didi

python - 根据句子中的单词对多个句子进行句子分类

转载 作者:太空宇宙 更新时间:2023-11-03 20:44:47 25 4
gpt4 key购买 nike

data = ["my web portal is not working","online is better than offline", "i like going to pharmacy shop for medicines"]
words = ["web", "online"]

我想迭代句子并检查列表单词中是否存在任何单词。如果是,我想要每个句子都有一个类别,其他类别为“其他”。如果我从单词列表中给出单个单词,它就可以工作,但我想在单次运行中检查所有单词。

b = []
def ch_1(x,y):
for i in x:
if y in i:
b.append("web")
else:
b.append("others")
return b

出现错误:

in ' requires string as left operand, not list

最佳答案

此代码适用于words中任意数量的单词和data中的句子:

data = [
"my web portal is not working",
"online is better than offline",
"i like going to pharmacy shop for medicines"
]

words = ["web", "online"]


def ch_1(words, data):
categories = {sentence: [] for sentence in data}
for sentence in data:
for word in words:
if word in sentence: # and categories[sentence] == [] ((if you want exactly one category for each sentence))
categories[sentence].append(word)
for sentence in categories:
if categories[sentence] == []:
categories[sentence].append('others')
return categories

print(ch_1(words, data))
{
'i like going to pharmacy shop for medicines': ['others'],
'online is better than offline': ['online'],
'my web portal is not working': ['web']
}

关于python - 根据句子中的单词对多个句子进行句子分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666289/

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