gpt4 book ai didi

python - 关于处理大文件的建议 - python 或命令行?

转载 作者:行者123 更新时间:2023-11-28 19:40:44 24 4
gpt4 key购买 nike

给定两个文件,其中一个包含以下形式的条目:

label1 label2 name1
label1 label3 name2

和另一种形式:

label1 label2 name1 0.1 1000
label9 label6 name7 0.8 0.5

假设您想从文件二中提取那些前三个元素在文件一中出现在一行(重要顺序)中的行 - 关于如何快速完成的任何建议?

给出上述示例数据的任何此类脚本的输出文件将是:

label1 label2 name1 0.1 1000

我玩过python:

inp = open(file1.txt, 'r')
look_up = [i.split() for i in inp.readlines()]
inp.close()

inp = open('file2', 'wt')

holder = []

line = inp.readline()
while line:
line = line.split()
if [line[0], line[1], line[2]] in look_up:
holder.append(line)
line = inp.readline()

但这似乎需要一段时间。这些文件相当大。

谢谢!

最佳答案

您的 Python 版本相当低效,因为您测试的是列表中的成员资格,而不是集合或字典(即 O(n) 查找时间而不是 O(1))。

尝试使用 set 元组或 set 字符串。元组将是更好的选择,因为两个文件可以在不同的分隔符上拆分,但我认为您不会看到特别大的性能差异。 tuple('something'.split()) 与测试非常长的列表的成员资格相比,速度相对较快。

此外,无需调用 inp.readlines()。换句话说,你可以这样做

look_up = set(tuple(line.split()) for line in inp)

而且除了 tuple(line[:3]) 而不是 [line[0], line[ 1], 行 [2]].

实际上,grep 和 bash 非常适合这个...(未经测试,但应该可以。)

while read line
do
grep "$line" "file2.txt"
done < "file1.txt"

要查看哪个更快,我们可以 generate some test data (file1.txt 中约有 4500 个键,file2.txt 中有 1000000 行),并对同一事物的简单 python 版本进行基准测试(大致...将打印这些行与 grep 版本的顺序不同。)。

with open('file1.txt', 'r') as keyfile:
lookup = set(tuple(line.split()) for line in keyfile)

with open('file2.txt', 'r') as datafile:
for line in datafile:
if tuple(line.split()[:3]) in lookup:
print line,

事实证明,python 版本快了约 70 倍:

jofer@cornbread:~/so> time sh so_temp149.sh > a

real 1m47.617s
user 0m51.199s
sys 0m54.391s

对比

jofer@cornbread:~/so> time python so_temp149.py > b

real 0m1.631s
user 0m1.558s
sys 0m0.071s

当然,这两个示例以完全不同的方式解决问题。我们实际上是在比较两种算法,而不是两种实现。例如,如果我们在 file1 中只有几行关键行,那么 bash/grep 解决方案很容易胜出。

(bash 是否有某种带有 O(1) 查找成员资格的内置容器?(我认为 bash 4 可能有一个哈希表,但我对此一无所知......)这会很有趣尝试在 bash 中实现与上面的 python 示例类似的算法......)

关于python - 关于处理大文件的建议 - python 或命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7325949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com