繁体   English   中英

在Python中为每条输出行编号

[英]Numbering each output line in Python

python:读取文件,然后每行重复两次,将输出行编号

示例:给定此文件:

Invictus

Out of the night that covers me
Black as the pit from pole to pole
I thank whatever gods there may be
For my unconquerable soul

这是输出:

1 Invictus
1 Invictus
2
2
3 Out of the night that covers me
3 Out of the night that covers me
4 Black as the pit from pole to pole
4 Black as the pit from pole to pole
5 I thank whatever gods there may be
5 I thank whatever gods there may be
6 For my unconquerable soul
6 For my unconquerable soul

这是我到目前为止的代码,我还无法弄清楚在每行加上双编号所需的循环:

fileicareabout = open("ourownfile","r")
text = fileicareabout.readlines()
count = len(open("ourownfile").readlines(  ))
fileicareabout.close()
def linecount(ourownfile):
    count = 0
    for x in open("ourownfile"):
        count += 1
    return count

for words in text:
    print (str(linecount) + words) * 2
print

您是说在粘贴每行两次时需要增加编号吗? 所以它必须是:1 Invictus

2罪犯

3

4

5覆盖我的夜晚

如果是这样,您的循环应如下所示:

count = 0
for words in text:
      print(str(count) + words)
      count += 1
      print(str(count) + words)
      count += 1

乘法运算符( * )可能很方便。

例:

>>> '15 hello world\n' * 2
'15 hello world\n15 hello world\n'

遵循相同的逻辑:

counter = 1
with open('input.txt') as input_file:
    with open('output.txt', 'w') as output_file:
        for line in input_file:
            output_file.write( '{} {}'.format(counter, line) * 2  )
            counter += 1

input.txt:

hello
world
my
name
is
Sait

output.txt:

1 hello
1 hello
2 world
2 world
3 my
3 my
4 name
4 name
5 is
5 is
6 Sait
6 Sait

您可以使用枚举来保持您的行号计数:

with open("ourownfile") as f:
    for line_no, line in enumerate(f, 1):
        print "{} {}".format(line_no, line)*2,

或使用更新的打印功能(python 3必需):

from __future__ import print_function

with open("ourownfile") as f:
    for line_no, line in enumerate(f, 1):
        print("{} {}".format(line_no, line)*2, end='')

要获得确切的输出,请跳过第一行:

with open("ourownfile") as f:
    for line_no, line in enumerate(f):
        if line_no == 0:
            continue
        print("{} {}".format(line_no, line)*2, end='')

暂无
暂无

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

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