2024-03-28 22:59:23 发布
网友
我有一个文件,包含数字和字符串,就像这样。你知道吗
1 something ASDF 1,2,3,4,5 2 something2 ASDFG 1,2,5,8,9 etc
在something和ASDF之间有一个标签
我想在“简单”行之后写两个标签。 输出应相同:
1\t\t something ASDF 1,2,3,4,5 2\t\t something2 ASDFG 1,2,5,8,9 etc
我该怎么做?你知道吗
三线解决方案
with open('a-file') as f: for i, l in enumerate(f): print "%s%s" % (l[:-1], '\t\t' if i % 2 == 0 else '')
试试这个:
#!/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()
输出(cortesy of cat -t):
cat -t
1^I^I something ASDF 1,2,3,4,5 2^I^I something2 ASDFG 1,2,5,8,9 etc
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
if re.search('^\d+$', line) != None
三线解决方案
试试这个:
输出(cortesy of
cat -t
):str.isdigit()
正则表达式替代:
if re.search('^\d+$', line) != None
相关问题 更多 >
编程相关推荐