索引器错误:列表索引超出范围(试图用另一个txt文件查找并替换一个txt文件的元素

2024-10-03 04:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

从这里开始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)

Tags: 文件txt脚本outputcountline数字程序员
1条回答
网友
1楼 · 发布于 2024-10-03 04:33:56

之所以引发IndexError,是因为在循环的每个迭代中都在增加count,但没有根据pllines列表实际包含的值的数量添加上限。当循环到达len(pllines)时,应该中断循环以避免错误

另一个您可能没有注意到的问题是re.sub()方法的使用。它返回一个带有适当替换项的新字符串,并且不修改原始字符串

如果该模式在字符串中不存在,它将返回原始模式本身。因此,您的nTemplate列表可能从未附加任何替换的字符串。除非在行中找到模式时需要执行其他操作,否则可以去掉if条件(如下面的示例所示)

因为priceValue对象对于所有行都是相同的,所以可以将它移到循环之外

以下代码应起作用:

nTemplate = [" "]
output = open(r'C:\Users\Sammy\Downloads\output.txt','rw+')

count = 0
priceValue = re.compile(r'107.5')

for line in templateImport:
    if count == len(pllines):
        break
    nTemplate.append(priceValue.sub(pllines[count], line))
    count = count + 1
    print(nTemplate)

相关问题 更多 >