私信  •  关注

Samha'

Samha' 最近创建的主题
Samha' 最近回复了
5 年前
回复了 Samha' 创建的主题 » 使用python从文本文件提取内容时出现问题

错误原因:

data_row 是一个列表 6 元素。

number_columns = 6
# ...
    data_row = [''] * number_columns  # [''] * 6

index 将随每次迭代而增加,其中 first_column_done = True 。但是 first_column_done True 什么时候 : 在一个单词中遇到,即

if ':' in w:
    first_column_done = True

因此,对于之后的每次迭代 第一列完成 转动 , 指数 将递增,直到超过 这是名单的范围 数据行 .

def row(l):
    l = l.split()
    number_columns = 6
    if len(l) >= number_columns: 
        data_row = [''] * number_columns
        first_column_done = False
        index = 0
        for w in l:
            if not first_column_done:
                data_row[0] = ' '.join([data_row[0], w])
                if ':' in w:
                    first_column_done = True
            else:
                index += 1
                data_row[index] = w    # error pos.

换言之,对于包含大于 6 - index 在第一次发生 : 在那行的一个字之内。


修复:

使用 split(':') list comprehension 和蟒蛇一样 tertiary operator .

def row(l):
    row = [ col.strip() for col in l.split(':') ]
    row[2:] = row[2].split()
    return [ row[i] if i < len(row) else '' for i in range(6) ]