1

我有一个文件,包含数字和字符串,就像这样。

1
something ASDF 1,2,3,4,5
2
something2 ASDFG 1,2,5,8,9
etc

在某物和 ASDF 之间有一个标签

我想在“简单”行之后写两个标签。输出应该相同:

1\t\t
something ASDF 1,2,3,4,5
2\t\t
something2 ASDFG 1,2,5,8,9
etc

我怎样才能做到这一点?

4

4 回答 4

2

尝试这个:

#!/usr/bin/env python

with open('f1') as fd:
    for line in fd:
        if line[0].isdigit():
            print line.strip() + '\t\t'
        else:
            print line.strip()

输出(由 提供cat -t):

1^I^I
something ASDF 1,2,3,4,5
2^I^I
something2 ASDFG 1,2,5,8,9
etc
于 2013-06-13T16:34:51.530 回答
2
with open('a-file', 'r+') as f:
    lines = []
    for line in f:
        if line.strip().isdigit():
            line = line.rstrip() + '\t\t\n'
        lines.append(line)
    f.seek(0)
    f.writelines(lines)

str.isdigit()

正则表达式替代:if re.search('^\d+$', line) != None

于 2013-06-13T16:33:38.320 回答
0

三行解决方案

with open('a-file') as f:
    for i, l in enumerate(f):
        print "%s%s" % (l[:-1], '\t\t' if i % 2 == 0 else '')
于 2013-06-13T17:10:59.897 回答
0

两行:

with open('f1') as f:
    ['%s%s' % (l.strip(), '\t\t' if l[0].isdigit() else '') for l in f]
于 2013-06-13T18:52:42.093 回答