迭代循环中的字符串格式问题

2024-04-19 02:10:46 发布

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

我正在尝试重新格式化一些数据,并将其保存到python的输出文件中。I.strip()从原始行中删除每一行,并将其附加到列表中。我用需要添加到原始数据中的值创建第二个列表(修改包含原始数据),并在需要传入原始数据列表中的值时使用字符串格式运算符对其进行迭代,将修改后的数据写入输出文件。输出需要在输出的每个记录中只插入一次显示的信息,这样就不是1:1的输出(原始行到输出行),我相信这就是我遇到问题的地方。下面是我的代码示例。。。你知道吗

原始数据:

Client
#ofrecords(as an integer)
Line1ofrecord1
Line2ofrecord1
....
Line1ofrecord2
Line2ofrecord2
....
End

代码:

def shouldbesimple(originalfile):
    inputfile = open(originalfile, "r")
    outputfile = open('finaloutput.txt', "w")
    nowhitespace = originalfile.strip()
    Client = nowhitespace.pop(0)
    Counter = nowhitespace.pop(0)  (each record has exactly the same number of lines)

    #at this point only record information remains in list..

    Header = "stuff at beginning of each record in output"
    Insertclient = "NEEDED {1} CHANGES"
    Line1 = "THINGS I {0} MUST ADD"
    Footer = "stuff at end of each record in output"
    thingstoadd = [Header, Line1, Insertclient, Footer]
    while counter > 0 :
        writetofile = ""
        for element in thingstoadd:
            writetofile = element.format(nowhitespace.pop(0), Client)
            outputfile.write(writetofile + "\n")
        counter = counter - 1
    inputfile.close()
    outputfile.close()

一切都按预期进行,直到我开始迭代添加。。你知道吗

数据没有按预期排列,我得到一个“从空列表弹出”错误。打印writetofile向我显示python在每次迭代中都在format语句中运行nowhitespace.pop(0)操作,而不仅仅是当{0}出现在相关元素中时。你知道吗

有没有更合适的方法将原始信息传递到字符串数据中,或者防止.pop()操作在每个元素上发生?你知道吗


Tags: of数据inclient列表原始数据counterrecord
1条回答
网友
1楼 · 发布于 2024-04-19 02:10:46

与其试着调试你的代码,不如让我告诉你我将如何做我认为你想做的事情。你知道吗

import itertools

# from itertools recipes in the docs
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x')  > ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def shouldbesimple(originalfile):
    with open(originalfile) as inputfile, open('finaloutput.txt', "w") as outputfile:
        client = next(inputfile).rstrip()
        count = int(next(inputfile).rstrip())
        groups = grouper(inputfile, 4)

        Header = "stuff at beginning of each record in output"
        Insertclient = "NEEDED {1} CHANGES"
        Line1 = "THINGS I {0} MUST ADD"
        Footer = "stuff at end of each record in output"
        thingstoadd = [Header, Line1, Insertclient, Footer]

        for _ in range(count):
            for fmt, line in zip(thingstoadd, next(groups)):
                outputfile.write(fmt.format(line.rstrip(), Client) + '\n')

使用此输入:

Client
2
Line1ofrecord1
Line2ofrecord1
Line3ofrecord1
Line4ofrecord1
Line1ofrecord2
Line2ofrecord2
Line3ofrecord2
Line4ofrecord2
End

我得到这个输出:

THINGS I Line2ofrecord1 MUST ADD
NEEDED Client CHANGES
stuff at end of each record in output
stuff at beginning of each record in output
THINGS I Line2ofrecord2 MUST ADD
NEEDED Client CHANGES
stuff at end of each record in output

相关问题 更多 >