gpt4 book ai didi

python - 使用 Python 的 replace() 方法实现停用词功能

转载 作者:太空宇宙 更新时间:2023-11-04 10:55:28 25 4
gpt4 key购买 nike

我正在尝试从字符串列表中的每个元素中去除子字符串。我无法弄清楚如何处理具有多个我要删除的子字符串(停用词)的字符串。

wines = ("2008 Chardonnay", "Cabernet Sauvignon 2009", "Bordeaux 2005 Cotes du Rhone")
stop_words = ("2005", "2008", "2009", "Cotes du Rhone")
result = []

for wine in wines:
for stop in stop_words:
if stop in wine:
x = wine.replace(stop, "")
result.append(x)

print result

将 if 语句更改为 for 或 while 会返回无用信息或挂起。有什么建议吗?

最佳答案

一点点缩进和改变周围的变量会解决你的问题

for wine in wines:
glass=wine #Lets pour your wine in a glass
for stop in stop_words:
if stop in glass: #Is stop in your glass?
#Replace stop in glass and pour it in the glass again
glass = glass.replace(stop, "")
result.append(glass) #Finally pour the content from your glass to result


result
[' Chardonnay', 'Cabernet Sauvignon ', 'Bordeaux ']

如果您喜欢冒险,可以使用正则表达式。我相信在这种情况下,正则表达式可能比简单循环更快

>>> for wine in wines:
result.append(re.sub('('+'|'.join(stop_words)+')','',wine))

>>> result
[' Chardonnay', 'Cabernet Sauvignon ', 'Bordeaux ']
>>>

或者将其作为列表理解

>>> [re.sub('('+'|'.join(stop_words)+')','',wine) for wine in wines]
[' Chardonnay', 'Cabernet Sauvignon ', 'Bordeaux ']
>>>

关于python - 使用 Python 的 replace() 方法实现停用词功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092337/

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