如何仅在第一列中移除下划线('_')及其前面的数字

1 投票
4 回答
2395 浏览
提问于 2025-04-16 13:31

我一直在尝试去掉下划线('_')后面跟着的数字。
这是我文本文件中的第一行。

JP_001033692.1_551  N   -1  NO  99.5425%    0.0022875

我想从 "JP_001033692.1_551" 中去掉 "_551",而不影响后面列中的其他内容。

期望的结果是:

JP_001033692.1  N   -1  NO  99.5425%    0.0022875

这是我的代码:

fname = open(raw_input('Enter input filename: '),'r' )
outfile = open('decValues.txt','w')

for line in fname:
    line = re.sub('[\(\)\{\}\'\'\,<>]','', line)
    fields = line.rstrip("\n").split()
    outfile.write('%s  %s %s  %s %1.4f\n' % (fields[0],fields[1],fields[2],fields[3],(float(fields[5]))))

谢谢大家的帮助。
Kesh

相关问题:

4 个回答

0

这段代码应该能满足你的需求:

re.sub(r'^([^ ]*)(_[0-9]*)( +)', r'\1\3', line)

在Python的交互式环境中测试:

>>> import re
>>> line = 'JP_001033692.1_551  N   -1  NO  99.5425%    0.0022875'
>>> re.sub(r'^([^ ]*)(_[0-9]*)( +)', r'\1\3', line)
'JP_001033692.1  N   -1  NO  99.5425%    0.0022875'
1

str.rpartition(sep)¶ 这个方法会在字符串中最后一次出现的分隔符sep处进行切分。

s = "this_is_a_string"

split_s = s.rpartition('_')

split_s

('this_is_a', '_', 'string')

split_s[0]

'this_is_a'

0

这样就可以了:

re.sub(r"(\.\d+)_\d+", r"\1", line)

撰写回答