我有一个大文本文件,
其中每一行都根据定义的语法(用正则表达式处理)。
我收到以下错误:
remainder = '{} {} '.format(*pieces[-1])
IndexError: list index out of range
在这段代码上:
def open_delimited(filename, args):
with open(filename, args, encoding="UTF-16") as infile:
chunksize = 10000
remainder = ''
for chunk in iter(lambda: infile.read(chunksize), ''):
pieces = re.findall(r"(\d+)\s+(\d+_\d+)\s+(((post)\s+1)|((\d+_\d+_\d+)\s+(comment)\s+2))(.+)(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})(.*)", remainder + chunk, re.IGNORECASE)
for piece in pieces[:-1]:
yield piece
remainder = '{} {} '.format(*pieces[-1])
if remainder:
yield remainder
filename = 'data/AllData_2000001_3000000.txt'
for chunk in open_delimited(filename, 'r'):
for j in range(len(chunk)):
print(chunk[j])
当我限制迭代次数时,代码工作正常。
i = 0
for chunk in open_delimited(filename, 'r'):
if (i <= 1000):
for j in range(len(chunk)):
print(chunk[j])
else:
break
i += 1