从这里开始python程序员。我目前正忙于编写一个小的python脚本,它将打开一个txt源文件,用正则表达式(本例中是107.5)在源文件中找到一个特定的数字,并最终用一个新的数字替换107.5。新的数字来自第二个包含30个数字的txt文件。每次替换一个数字时,脚本都使用下一个数字进行替换。尽管命令提示符看起来确实打印了一个成功的find and replace,但在第30个循环之后,“IndexError:list index out of range”出现了
我的预感是我必须以某种方式限制我的循环,比如“因为我在x范围内”。但是,我不确定这应该是哪个列表,以及如何将循环限制合并到当前代码中。非常感谢您的帮助
nTemplate = [" "]
output = open(r'C:\Users\Sammy\Downloads\output.txt','rw+')
count = 0
for line in templateImport:
priceValue = re.compile(r'107.5')
if priceValue.sub(pllines[count], line) != None:
priceValue.sub(pllines[count], line)
nTemplate.append(line)
count = count + 1
print('found a match. replaced ' + '107.5 ' + 'with ' + pllines[count] )
print(nTemplate)
else:
nTemplate.append(line)
之所以引发
IndexError
,是因为在循环的每个迭代中都在增加count
,但没有根据pllines
列表实际包含的值的数量添加上限。当循环到达len(pllines)
时,应该中断循环以避免错误另一个您可能没有注意到的问题是
re.sub()
方法的使用。它返回一个带有适当替换项的新字符串,并且不修改原始字符串如果该模式在字符串中不存在,它将返回原始模式本身。因此,您的
nTemplate
列表可能从未附加任何替换的字符串。除非在行中找到模式时需要执行其他操作,否则可以去掉if
条件(如下面的示例所示)因为
priceValue
对象对于所有行都是相同的,所以可以将它移到循环之外以下代码应起作用:
相关问题 更多 >
编程相关推荐