【问题标题】:How can I prevent this code from crashing when I try to use it with large files?当我尝试将其用于大文件时,如何防止此代码崩溃?
【发布时间】:2021-11-09 16:32:32
【问题描述】:

我对 Python 很陌生,我正在尝试使用此代码。如果我必须用几行转换文件,一切正常,但如果我用 500 MB 的文件进行转换,它会崩溃。

import re
import num2words

with open('num.txt') as f_input:
     text = f_input.read()
text = re.sub(r"(\d+)", lambda x : num2words.num2words(int(x.group(0))), text)
with open('word.txt','w') as f_output:
     f_output.write(text)

我能做些什么让它比这更进一步?是内存问题和读行吗?

【问题讨论】:

  • edit您的问题将其标题翻译成英文。
  • 用您自己的话来说,您认为f_input.read() 是做什么的?你能想到其他读取和处理文件的方法吗? “是不是内存问题”你有没有试过在运行代码时检查 Python 使用了多少内存?

标签: python python-3.x


【解决方案1】:

您当前正在读取整个输入,然后处理整个输入。这需要将所有内容加载到内存中。

改为逐行处理并随时保存到输出文件:

import re
from num2words import num2words

with open('num.txt') as f_input, open('word.txt', 'w') as f_output:
    for line in f_input:
        line = re.sub(r"(\d+)", lambda x : num2words(int(x.group(0))), line)
        f_output.write(line)

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多