【发布时间】:2018-09-06 15:06:47
【问题描述】:
我有一个包含大约 1.3 亿字的大型文本文件用于测试目的。为了计算文件中的单词,我编写了以下代码,我称之为“普通解决方案”。
#!/usr/bin/python3.7
with open('v_i_m_utf8.txt') as infile:
words=0
for line in infile:
wordslist = line.split()
words += len(wordslist)
print(words)
我现在得到的结果:
tony@lenox:~$ time ./counting.py
134721552
real 0m29,391s
user 0m28,907s
sys 0m0,400s
tony@lenox:~$
请问,是否可以使用一些 python 内部技巧来更快地处理字符串?
我只需要数单词并尽可能快地完成 Python 运行时。
【问题讨论】:
-
没有用python,你试过
wc -w v_i_m_utf8.txt吗?这是一个成熟的专门编写的程序,可能是用 C 语言编写的。 -
谢谢,但我很想在 Python 中仅针对这种情况搜索解决方案,没有标准的 unix utils
-
@cdarke 在我的硬件上的执行时间
tony@lenox:~$ time wc -w v_i_m_utf8.txt 134721552 v_i_m_utf8.txt real 0m55,585s user 0m54,192s sys 0m0,552s -
@cdarke, $ time wc -w v_i_m.utf 134721552 v_i_m.utf wc -w v_i_m.utf 33.26s user 0.18s system 99% cpu 33.461 total from PC with better performance that mine.跨度>
标签: python string python-3.x performance