簡體   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