繁体   English   中英

如何替换文本文件中的第一列?

[英]How to replace first column in text file?

我有这样的文件

6     5     1         2.364       0.022
6     5     2        30.364       2.866
6     5     5         2.351       0.022
6     5     6        44.606       2.866
6     6     1         2.372       0.022
6     6     2        33.290       2.866
6     6     5         2.290       0.022
6     6     6        43.799       2.866
6     7     1         2.414       0.022
6     7     2        37.071       2.866
6     7     5         2.281       0.022

我想把6改成1,我想到了

line.contains

但 6 也出现在其他列中。

我建议使用sed而不是 Python。

sed -e 's/^6/1/' input.txt > output.txt
import re
with open(...) as f:
    print re.sub('^6', '1', f.read(), flags=re.MULTILINE)

s = '''6     5     1         2.364       0.022
6     5     2        30.364       2.866
6     5     5         2.351       0.022
6     5     6        44.606       2.866
6     6     1         2.372       0.022
6     6     2        33.290       2.866
6     6     5         2.290       0.022
6     6     6        43.799       2.866
6     7     1         2.414       0.022
6     7     2        37.071       2.866
6     7     5         2.281       0.022'''

import re
print re.sub('^6', '1', s, flags=re.MULTILINE)

如果你不想使用re ,你可以尝试(虽然我建议使用re ):

lines = []
for line in open(...):
    parts = line.split()
    parts[0] = '1'
    lines.append('\t'.join(parts))
 print '\n'.join(lines)

或者:

lines = []
for line in open(...):
    lines.append(line.replace('6', '1', 1))
 print '\n'.join(lines)

暂无
暂无

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

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