Python:文件格式

时间:2010-03-06 16:10:59

标签: python file formatting

我有一个for循环,它引用一个字典并打印出与该键相关的值。代码如下:

for i in data:
    if i in dict:
        print dict[i],

如何格式化输出以便每60个字符创建一个新行?以及旁边的字符数,例如:

  

0001   MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP
  0061   DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH
  0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ

4 个答案:

答案 0 :(得分:1)

这是一个挑剔的格式问题,但我认为以下代码:

import sys

class EveryN(object):
  def __init__(self, n, outs):
    self.n = n        # chars/line
    self.outs = outs  # output stream
    self.numo = 1     # next tag to write
    self.tll = 0      # tot chars on this line
  def write(self, s):
    while True:
      if self.tll == 0: # start of line: emit tag
        self.outs.write('%4.4d ' % self.numo)
        self.numo += self.n
      # wite up to N chars/line, no more
      numw = min(len(s), self.n - self.tll)
      self.outs.write(s[:numw])
      self.tll += numw
      if self.tll >= self.n:
        self.tll = 0
        self.outs.write('\n')
      s = s[numw:]
      if not s: break

if __name__ == '__main__':
  sys.stdout = EveryN(60, sys.stdout)
  for i, a in enumerate('abcdefgh'):
    print a*(5+ i*5),

显示了如何操作 - 运行时作为主脚本运行的输出(五个a,十个b等,中间有空格)是:

0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee
0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg
0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
0181 hhhhhhh

答案 1 :(得分:0)

好像你正在寻找textwrap

  

textwrap模块提供了两个便利功能,wrap()和   fill(),以及TextWrapper,完成所有工作的类,以及   实用函数dedent()。如果你只是包装或填充一个或   两个文本字符串,方便功能应该足够好;   否则,您应该使用TextWrapper的实例来提高效率。

答案 2 :(得分:0)

# test data
data = range(10)
the_dict = dict((i, str(i)*200) for i in range( 10 ))

# your loops as a generator
lines = ( the_dict[i] for i in data if i in the_dict )

def format( line ):
    def splitter():
        k = 0
        while True:
            r = line[k:k+60] # take a 60 char block
            if r: # if there are any chars left
                yield "%04d %s" % (k+1, r) # format them
            else:
                break
            k += 60
    return '\n'.join(splitter()) # join all the numbered blocks

for line in lines:
        print format(line)

答案 3 :(得分:0)

我没有在实际数据上测试它,但我相信下面的代码可以完成这项工作。它首先构建整个字符串,然后一次输出一个60个字符的行。它使用range()的三参数版本来计算60。

s = ''.join(dict[i] for i in data if i in dict)
for i in range(0, len(s), 60):
    print '%04d %s' % (i+1, s[i:i+60])