gpt4 book ai didi

python - 我收到此错误 : must be str, 不是 Python 中的生成器

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:40 24 4
gpt4 key购买 nike

我正在使用 python,这是我的一段代码

with open("Create indicators.sas", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace((m for m in num_list),( n for n in num_list2)))

其中 num_list 是单词列表,num_list2 是我需要替换的另一个单词列表。

当我尝试运行整个代码时,我收到以下消息:

类型错误:必须是 str,而不是生成器

最佳答案

# Stolen from https://stackoverflow.com/q/12624623/8593865    
replacements = zip(num_list, num_list)

with open("Create indicators.sas", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
for before, after in replacements:
fout.write(line.replace(before, after)

说明:

它的作用是首先合并两个列表,以便您得到一个其中每个项目都是子列表的列表。子列表中的第一项是您要替换的内容,第二项是其替换内容。

for before, after in replacements: 解压这两项并让您将它们用作变量

replace 不接受列表,尽管这是一个好主意。您必须为要查找和替换的每个字符串调用replace。您收到的原始错误是因为列表推导式是生成器对象,除非您将它们转换为列表或元组,并且 replace 不采用生成器。但是,您的代码无论如何都无法正常运行,因为不幸的是您无法批量替换这样的字符串中的子字符串。

关于python - 我收到此错误 : must be str, 不是 Python 中的生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974760/

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