我正在使用一个看起来像这样的文本文件:
rs001 电子电气设备 /n rs008 电子电气设备 /n rs345EEE/n rs542 CHG /n re432 CHG/n
我希望能够将第 2 列中共享相同值的所有行折叠成一行(例如,rs001 rs008 rs345 EEE
)。有没有一种简单的方法可以使用 unix 文本处理或 python 来做到这一点?
谢谢
#!/usr/bin/env python
from __future__ import with_statement
from itertools import groupby
with open('file','r') as f:
# We define "it" to be an iterator, for each line
# it yields pairs like ('rs001','EEE')
it=(line.strip().split() for line in f)
# groupby does the heave work.
# lambda p: p[1] is the keyfunction. It groups pairs according to the
# second element, e.g. 'EEE'
for key,group in groupby(it,lambda p: p[1]):
# group might be something like [('rs001','EEE'),('rs008','EEE'),...]
# key would be something like 'EEE', the value that we're grouping by.
print('%s %s'%(' '.join([p[0] for p in group]),key))
这是你的傻瓜
$ awk '{a[$2]=a[$2]FS$1}END{for(i in a)print i,a[i]}' file
EEE rs001 rs008 rs345
CHG rs542 re432
一种选择是构建一个以第 2 列数据为键的字典:
from collections import defaultdict #defaultdict will save a line or two of code
d = defaultdict(list) # goal is for d to look like {'EEE':['rs001', 'rs008', ...
for line in file('data.txt', 'r'):
v, k = line.strip().split()
d[k].append(v)
for k, v in d.iteritems(): # print d as the strings you want
print ' '.join(v+[k])
这种方法的优点是它不需要将第 2 列术语分组在一起(尽管问题中没有直接指定第 2 列是否预先分组)。