【问题标题】:creating single line from mulitplelines from huge text file in python or others based on id从 python 中的巨大文本文件或其他基于 id 的多行创建单行
【发布时间】:2018-01-10 15:29:11
【问题描述】:

我有一个非常大的文本文件(20GB),像这样的行,

1 Some text
1 More text
2 Text 
2 Follow up text
..
..
n

我想将文件转换成这样:

1, sometext, more text
2, text , followup text

我该怎么做python。我无法将整个文件保存在内存中。

【问题讨论】:

  • 这些是否已经按 id 排序?
  • 是,按 ID 排序
  • 你真的是要把 Some text 转换成 sometext 等吗?您需要定义为什么follow up text 被转换为followup text 的规则。但more text 仍然是more text(或清理您的示例)。另外,你试过什么?祝你好运。
  • 我需要清理示例。我对如何实现逻辑一无所知,即保留当前 ID 和最后一个 ID 的标签,并在到达最后一行 ID 时输出。

标签: python unix multiline readlines


【解决方案1】:

你可以使用itertools.groupby按照以下方式做某事:

from itertools import groupby
# from itertools import groupby, imap  # Python2 map returns a list

def tokens(line):
  return [t.strip() for t in line.strip().split(' ', 1)]

with open('infile.txt', 'r') as fin, open('outfile.txt', 'w') as fout:
  for k, g in groupby(map(tokens, fin), key=lambda t: t[0]):
  # for k, g in groupby(imap(tokens, fin), key=lambda t: t[0]):  # Py2
    fout.write(', '.join([k] + [x[1] for x in g]) + '\n')
    # not to be too silent
    print('Processing id: ' + k)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多