簡體   English   中英

IndexError:列表索引超出范圍。 (嘗試查找一個txt文件的元素並將其替換為另一個txt文件

[英]IndexError: list index out of range. (trying to find and substitute elements of one txt file with another txt file

在這里開始python程序員。 我目前堅持編寫一個小的python腳本,該腳本將打開txt源文件,並使用正則表達式(在這種情況下為107.5)在該源文件中找到一個特定的數字,並最終用一個新數字替換該107.5。 新號碼來自另一個包含30個數字的txt文件。 每次替換數字時,腳本都會使用下一個數字進行替換。 盡管命令提示符似乎確實可以打印出成功的查找和替換,但是在第30次循環后會出現“ IndexError:列表索引超出范圍” ...

我的飢餓感是,我必須以某種方式將循環限制為“ for i in 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對象對於所有行都是相同的,因此可以將其移到循環外。

下面的代碼應該工作:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM