Python:文件格式

2024-04-27 00:35:01 发布

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

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

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

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

0001 MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP
0061 DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH
0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ


Tags: 代码infordataif字典字符dict
3条回答

这是一个复杂的格式化问题,但我认为以下代码:

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等,中间有空格)时,输出为:

^{pr2}$
# 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)

我还没有在实际数据上测试过它,但我相信下面的代码可以做到这一点。它首先建立整个字符串,然后每次输出一个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])

相关问题 更多 >