【问题标题】:Find/replace in large datasets with Python使用 Python 在大型数据集中查找/替换
【发布时间】:2016-04-17 09:40:32
【问题描述】:

我有一个 3GB 的文件 a.txt,格式为:

a 20
g 33
e 312
....

还有一个b.txt 文件,它是a.txt 中字母表的映射:

e elephant
a apple
g glue
....

我想合并这两个文件来创建c.txt,比如:

apple 20
glue 33
elephant 312
...

我试图编写一个简单的 for 循环来做到这一点,但失败了。当我运行 python 文件时,它会运行 2 秒并停止。

【问题讨论】:

  • 究竟是什么让编写一个简单的for 循环变得不可能?只是不要将整个文件加载到内存中。不管怎样,这已经做了一百万次了,让我找一个副本。
  • @N.Wouda 我该怎么做?
  • @N.Wouda 非常感谢。
  • 我今天标记的太多了,但this 几乎是重复的。
  • @N.Wouda 我一直用这个,但是当数据集比正常大时它会很慢

标签: python


【解决方案1】:

这可以用像这样的字典来完成

mapping = {}
with open('b.txt') as f:
  for line in f:
    key, value = line.split()
    mapping[key] = value
with open('a.txt') as i:
  with open('c.txt', 'w') as o:
    for line in i:
      key, value = line.split()
      if key in mapping:
        print(value, mapping[key], file=o)

那么如果a.txt 是 3GB 呢?在现代台式计算机上,这仍然会非常快速地运行

【讨论】:

  • 你确定你没有弄错这两个文件吗? ab不应该反过来打开吗?
  • @N.Wouda 好的,我确实把它们弄混了。好收获!
  • @randomusername 我在 ipython 中尝试过,它甚至停止工作
【解决方案2】:

严格回答您的问题,这将在 a.txt 中逐行读取,扫描 b 以查找匹配项,将其写出,关闭 b,读取 a.txt 中的下一行,再次打开 b 等等。这个一次只能读取一行。我推断存在一对一的无序匹配。

def process(a,b,outpath):
    outref = open(outpath,'w')
    with open(a,'r') as fh:
        for line in fh:
            key,value = line.split()
            with open(b,'r') as fh_b:
                for b_line in fh_b:
                    bkey, bvalue = b_line.split()
                    if bkey == key:
                        outref.write(bvalue.strip() + ' ' + value.strip() + '\n')
                        continue
    outref.close()
    return 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-07-14
    • 2013-04-17
    • 1970-01-01
    • 2018-07-30
    • 2019-03-29
    相关资源
    最近更新 更多