0

我需要根据第一列中的 id 组合制表符分隔文件的第二列中的值。示例如下。最快的方法是什么。我可以使用 for 循环,遍历每一行,但我确信有一些聪明的方法可以做到这一点,我不知道。

596230  Other postop infection
596230  Disseminated candidiasis
596230  Int inf clstrdium dfcile
596230  Pressure ulcer, site NOS
2846079 Schizophrenia NOS-unspec
7800713 CHF NOS
7800713 Chr airway obstruct NEC
7800713 Polymyalgia rheumatica
7800713 DMII wo cmp nt st uncntr

进入

596230  Other postop infection, Disseminated candidiasis, Int inf clstrdium dfcile, Pressure ulcer, site NOS
2846079 Schizophrenia NOS-unspec
7800713 CHF NOS, Chr airway obstruct NEC, Polymyalgia rheumatica, DMII wo cmp nt st uncntr
4

3 回答 3

2

假设您在文件中有文本:

from collections import defaultdict
items = defaultdict(list)
with open("myfile.txt") as infile:
    for line in file:
        id, text = line.rstrip().split("\t")
        items[id].append(text)
for id in items:
    print id + "\t" + ", ".join(items[id])

这不会保持你id的 s 的原始顺序,但它确实保持了文本的顺序。

于 2012-10-05T13:14:30.783 回答
1

如果它们已经排序,您可以itertools.groupby()在分割线上使用来收集它们。如果它们未排序,则先对其进行排序。

于 2012-10-05T13:11:29.367 回答
1

您还可以考虑使用Python csv 模块来解析文件,因为您可以将其设置为使用逗号以外的字符(例如制表符,\t)作为分隔符。基本示例是这样的:

import csv
with open('myfile', 'rb') as f:
    reader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    for row in reader:
        print row

从那里您可以使用已经建议的选项之一将具有相同编号的所有项目组合在一起。

于 2012-10-05T14:11:28.067 回答