我有一个制表符分隔的文件,如下所示:
这是一个句子。艾布 这是什么 foo 酒吧。贝夫 你好,富酒吧等等黑羊。 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')]
最佳答案
But is it possible to do the same in python?
是的,你可以:
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))
would it be faster?
不太可能,cut是针对这种处理进行优化的C程序,Python是一种通用语言,具有很大的灵活性,但不一定很快。
不过,通过使用像我编写的算法这样的算法,您可能获得的唯一优势是您只需读取文件一次,而使用 cut 时,您将读取它两次。这可能会产生影响。
尽管我们需要运行一些基准测试才能达到 100%。
这是在我的笔记本电脑上进行的一个小基准测试,其值(value)如下:
>>> 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 版本确实更快,正如预期的那样;-)
关于python - 如何使用分隔符将csv文件分割成多个文件? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24550421/