python - 在 Python 中逐字读取一个非常大的文件

标签 python io large-files yield

我有一些非常大的文本文件 (>2g),我想逐字处理。这些文件是以空格分隔的文本文件,没有换行符(所有单词都在一行中)。我想获取每个单词,测试它是否是字典单词(使用 enchant),如果是,则将其写入新文件。

这是我现在的代码:

with open('big_file_of_words', 'r') as in_file:
        with open('output_file', 'w') as out_file:
            words = in_file.read().split(' ')
            for word in word:
                if d.check(word) == True:
                    out_file.write("%s " % word)

我看了lazy method for reading big file in python ,这建议使用 yield 分块读取,但我担心使用预定大小的 block 会在中间拆分单词。基本上,我希望 block 尽可能接近指定的大小,同时只在空格上分割。有什么建议吗?

最佳答案

将一个 block 的最后一个单词与下一个 block 的第一个单词组合:

def read_words(filename):
    last = ""
    with open(filename) as inp:
        while True:
            buf = inp.read(10240)
            if not buf:
                break
            words = (last+buf).split()
            last = words.pop()
            for word in words:
                yield word
        yield last

with open('output.txt') as output:
    for word in read_words('input.txt'):
        if check(word):
            output.write("%s " % word)

关于python - 在 Python 中逐字读取一个非常大的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372335/

相关文章:

python - 使用 to_sql 将数据从 pandas dataframe 导入 SQL 数据库时 PC 挂起

python - 在python中从大量xml文件中提取信息的最有效方法是什么?

python - 使用另一个 yaml 文件的内容更新

python - 导入错误: No module named 'users'

python - 什么是 "better"反向方法或反向内置函数?

ios - iOS 5 下的 Haskell : suppressing output

javascript - 使用 Javascript 读取多个文件会导致仅读取最后一个文件

python - “NoneType”对象没有属性 'clip' `` `cv2_imshow( )`` `

java - 服务器响应设置 boolean 值 true/false

java - 适用于 Java 的优秀且有效的 CSV/TSV 阅读器