gpt4 book ai didi

python - 从字符串中删除单词列表

转载 作者:IT老高 更新时间:2023-10-28 20:57:03 31 4
gpt4 key购买 nike

我有一个停用词列表。我有一个搜索字符串。我想从字符串中删除单词。

举个例子:

stopwords=['what','who','is','a','at','is','he']
query='What is hello'

现在代码应该去掉“什么”和"is"。但是在我的情况下,它会去除“a”和“at”。我在下面给出了我的代码。我可能做错了什么?

for word in stopwords:
if word in query:
print word
query=query.replace(word,"")

如果输入查询是“What is Hello”,我得到的输出是:
wht llo

为什么会这样?

最佳答案

这是一种方法:

query = 'What is hello'
stopwords = ['what', 'who', 'is', 'a', 'at', 'is', 'he']
querywords = query.split()

resultwords = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)

print(result)

我注意到如果单词的小写变体在列表中,您还想删除它,因此我在条件检查中添加了对 lower() 的调用。

关于python - 从字符串中删除单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25346058/

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