我正在使用具有以下结构的文本文件:

printer_name:
description = printer_description
library = printer_library
form = printer_form


数据库中的每台打印机都会重复此结构。

我正在处理的python脚本的所需输出如下所示:

'printer_name', 'printer_description', 'printer_library', 'printer_form'
'printer_name', 'printer_description', 'printer_library', 'printer_form'

...and so on for every printer record in the text file...


此时,在尝试将每个项目收集到每个记录的列表对象中时,我一直在构建所需的输出时遇到问题。

这是我一直在使用的最新版本:

f = input('Enter file name:')
fh = open(f)

lst = list()
for line in fh:
    line = line.strip()
    if len(line) == 0: continue

    elif line.startswith('description'):
        descList = line.split()
        description = ' '.join(descList[2:])
        lst.append(description)

    elif line.startswith('library'):
        libList = line.split()
        libraryItem = libList[2:]
        library = libraryItem[0]
        lst = lst.append(library)

    elif line.startswith('form'):
        formList = line.split()
        formItem = (formList[2:])
        form = formItem[0]
        lst = lst.append(form)

    else:
        printer = line[:-1]
        lst = lst.insert(0, printer)

print(lst)


此脚本返回Python的属性错误,指示“ NoneType”对象没有属性“ append”。这似乎是在我的第一个elif块中引用lst.append(description)语句,但是,当我注释掉其余的elif块并以这种方式运行脚本时,我可以生成一个描述项列表。

我在想,为了在获取所需输出的方式上获得列表的“列表”,我需要放置print(lst)语句,以便对其内置的每个打印记录进行调用自己的路线,但我在这方面也遇到了麻烦。

有谁愿意并且能够为我解决这个难题?

我真的很感激!

最佳答案

方法append返回None,因此当您尝试lst = lst.append(library)时,请将变量设置为None
全部替换:

lst = lst.append(library)
lst = lst.insert(0, printer)




lst.append(library)
lst.insert(0, printer)


如果您需要listlines
您可以尝试以下逻辑:

lines = list()
for line in fh:
    lst = list()
    # You code
    lines.append(lst)

关于python - 在输出每个列表之前,解析文本文件并将文本收集到列表对象中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46103250/

10-12 12:57
查看更多