我有一个以制表符分隔的文件:
这是一个句子。abb这是什么?贝芙你好啊,黑羊。abb我可以在unix终端中使用cut -f1
和cut -f2
拆分为两个文件:
this is a sentence.
what is this foo bar.
hello foo bar blah black sheep.
:
abb
bev
abb
但是在python中有可能做同样的事情吗?会更快吗?
我一直是这样做的:
[i.split('t')[0] for i in open('in.txt', 'r')]
但是在python中有可能做同样的事情吗?
yes you can:
l1, l2 = [[],[]]
with open('in.txt', 'r') as f:
for i in f:
# will loudly fail if more than two columns on a line
left, right = i.split('t')
l1.append(left)
l2.append(right)
print("n".join(l1))
print("n".join(l2))
会更快吗?
不太可能,cut是针对这种处理进行优化的C程序,python是一种通用语言,具有很大的灵活性,但不一定快。
但是,使用像我写的这样的算法可能得到的唯一好处是,您只需读取文件一次,而使用cut则需要读取两次。
虽然我们需要运行一些基准测试来达到100%。
在我的笔记本电脑上做了一个小的基准测试:
>>> timeit.timeit(stmt=lambda: t("file_of_606251_lines"), number=1)
1.393364901014138
和
% time cut -d' ' -f1 file_of_606251_lines > /dev/null
cut -d' ' -f1 file_of_606251_lines > /dev/null 0.74s user 0.02s system 98% cpu 0.775 total
% time cut -d' ' -f2 file_of_606251_lines > /dev/null
cut -d' ' -f2 file_of_606251_lines > /dev/null 1.18s user 0.02s system 99% cpu 1.215 total
等于1.990秒。
所以python版本确实更快,正如预期的那样;-)