gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:28 25 4
gpt4 key购买 nike

我有一些非常大的文本文件 (>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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com