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