简体   繁体   English

Python在一定数量的空行后打印文本

[英]Python Print text after certain number of blank lines

I have certain text that is in the format such as: 我有某些格式如下的文本:

    text:aaaaaaa
    text:bbbbbb
    text:cccccc

    text:ddddd
    text:eeeeee

    text:ffffff

I would like to print the text at: 我想在以下位置打印文本:

    text:fffff

How can some python code be written that counts the two spaces between the text and prints the text at text:fffff 如何编写一些python代码来计算文本之间的两个空格并在text:fffff上打印文本

>>> with open("foo.txt") as fin:
...     any(x.isspace() for x in fin) # skip to 1st blank line
...     any(x.isspace() for x in fin) # skip to 2nd blank line
...     next(fin)
... 
True
True
'    text:ffffff\n'

To skip past n blank lines 跳过n空行

>>> n = 2
>>> with open("t.txt") as fin:
...     for i in range(n):
...         any(x.isspace() for x in fin)
...     print next(fin)
... 
True
True
    text:ffffff

To do this way: 为此,请执行以下操作:

mydictonary = dict((k.strip(), v.strip()) for k,v in 
              (item.split(':') for item in s.split(' ')))

Here appy this things: 在这里贴上这个东西:

  • whitespace remove from each pairs: (k.strip(), v.strip()) 空格从每对中删除: (k.strip(), v.strip())
  • split each part into "<key> ", " <value>" pairs: item.split(':') 将每个部分分成"<key> ", " <value>"对: item.split(':')
  • split the string into "<key> - <value>" pairs using s.split(' ') 使用s.split(' ')将字符串拆分为"<key> - <value>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM