首页 > 解决方案 > 在 python 中处理大型文本文件

问题描述

我正在处理 2 个大文件。主文件有 2 个字段表示客户名称,第二个字段是客户 ID。我有第二个文件,它是第一个文件的子集,只有客户姓名。我希望找到我的子集文件中存在的名称的客户 ID。

第一个文件有 3000 万行,第二个文件有 500 万行。

我正在尝试使用字典来做到这一点,但这需要花费大量时间。

你能建议我一个更好的方法吗?

这是我的代码片段和我的文件中的几行。

主文件

#

约翰 2343245

卡里姆 126754

抢 6543289

维杰 2247861

山姆 2649860

……

子集第二个文件

山姆

约翰

def extract_info(sub_file,master_file):
    sub_fh = open(sub_file,'r',16777216)
    sub_inst_list = []
    for line in sub_fh:
        if line.startswith('#'):
            continue
        else:
            name = line.rstrip()
            sub_inst_list.append(name)
    sub_fh.close()


out_file = "results.rpt"
outf = open(out_file,'w')
bunchsize = 10000
bunch = []
master_fh = open(master_file,'r',16777216)
for line in master_fh:
    if line.startswith('#'):
        continue
    else:
        data = line.split()
        name = data[0]
        if str(data[1]) == "n/a":
            continue
        else:
            if name in sub_inst_list:
                id = str(data[1])
                line = "%-80s %-15s\n" % (name, id)
                bunch.append(line)
                if len(bunch) == bunchsize: 
                    outf.writelines(bunch)
                    bunch= []
                outf.writelines(bunch)
  master_fh.close()
  outf.close()

标签: pythondictionarylarge-files

解决方案


更好的方法是将主文件中的所有数据放入数据库中,然后根据第二个文件中的键查找值:

import sqlite3

conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute("CREATE TABLE data (Name VARCHAR(255), ID INT)")

# fill the DB
with open("master.txt") as f:
    for line in f:
        c.execute("INSERT INTO data VALUES (?, ?)", line.split())
conn.commit()

# search for data
with open("slave.txt") as f:
    for line in f:
        print(c.execute("SELECT ID FROM data WHERE Name=:search_name", {"search_name": line.strip()}).fetchall())

conn.close()

推荐阅读