有没有办法提高在Python中读取文本文件的速度?

时间:2013-07-17 15:53:15

标签: python performance file

我正在读一个587 kb的文件,其中包含来自a-z的单词,如: AA BB CC ...等等... 现在,无论我编写什么代码,它都需要38秒才能读取文件!

with open('dictionary.txt', encoding = 'utf-8') as dictionary:
      dictionary.read().splitlines()

我的问题是:如何在不到4秒的时间内读取文件?此外,它必须返回列表中的所有单词。


问题已解决
“我得到了它!而不只是在问题中并且选择一个随机的单词,而不是打印所有的单词,愚蠢的我。现在,当我这样做时,它会在不到一秒钟内给我这个词:pastie .org / 8149529“

6 个答案:

答案 0 :(得分:2)

这应该需要更少的内存,因为它遍历行:

words = []
with open('dictionary.txt', encoding='utf-8') as dictionary:
    for line in dictionary:
        words.extend(line.split())

答案 1 :(得分:0)

获取文件中所有单词的最佳方法:

>>> with open('dictionary.txt', encoding='utf-8') as dictionary:
    words = dictionary.read().split()

答案 2 :(得分:0)

with open('dictionary.txt', encoding = 'utf-8') as dictionary:
     list(dictionary)

也许???如果需要长时间好奇您的规格是什么

你可以发布结果

import time
s = time.time()
with open('dictionary.txt', encoding = 'utf-8') as dictionary:
     x=list(dictionary)
print time.time()-s

答案 3 :(得分:0)

read()正在将整个文件读入一个字符串,然后通过复制数据来拆分行。

按行流式传输数据有助于:

with open( 'dictionary.txt', .... ) as dictionary:
    for line in dictionary:
         <do something with the line>

文件结构为每行一个单词吗? 如果不是,那么可能会更加分裂。

答案 4 :(得分:0)

我在a 4 MB text file上运行了你的代码片段,在我的笔记本电脑上用OS X花了大约半秒钟。它确实打印出整个文件(出乎意料地很快),在Windows上我希望这会非常慢。尝试将结果保存到变量中,以便不打印它:

with open('dictionary.txt', encoding = 'utf-8') as dictionary:
    lines = dictionary.read().splitlines()

答案 5 :(得分:0)

你说“立刻得到了消息,但它又一次要打印出单词列表。”

因此,您提出的问题不存在。继续使用您发布的代码,并意识到打印到控制台需要时间,特别是如果您逐行打印,而不是一次保留/创建换行符和打印。