gpt4 book ai didi

python - Python 中的列表在使用替换方法时不维护值

转载 作者:行者123 更新时间:2023-11-30 22:26:57 24 4
gpt4 key购买 nike

所以,我编写了这段代码,它接收一个文件(在我的例子中,是一堆特朗普推文)。然后,我进入一个循环,我认为我可以通过一次替换关键词来递归地继续变形这些推文(例如“俄罗斯”而不是“美国”,让美国再次伟大)。但是,该列表不维护替换的值;因此,如果我进行一项替换,旧的替换项就会被删除。如何在这个循环中继续使该文本变形,一次一步?

load_text = raw_input("filename: ")
f = open(load_text)

text = []
for line in f:
text.append(line)

loop = 1
while loop == 1:

replace_this = raw_input("replace this: ")
with_this = raw_input("with this: ")

for line in text:
line = line.replace(replace_this, with_this)
print line

最佳答案

变量line当您执行 line = line.replace(replace_this, with_this) 时会重新分配,它实际上并没有更新 text 的内容。分配text内的实际行你可以这样做:

for idx, line in enumerate(text):
text[idx] = line.replace(replace_this, with_this)
print text[idx]

关于python - Python 中的列表在使用替换方法时不维护值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47086424/

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