• chardet检测文件编码,使用生成器逐行读取文件


    detect_encoding 函数使用 chardet 来检测文件的编码。然后,在 process_large_file 函数中,根据检测到的编码方式打开文件。这样,你就能够更准确地处理不同编码的文件。

    1. import chardet
    2. def detect_encoding(file_path):
    3. with open(file_path, 'rb') as f:
    4. result = chardet.detect(f.read())
    5. return result['encoding']
    6. def process_line_with_line_number(line, line_number):
    7. # 占位符函数,你需要在这里定义自己的逻辑
    8. # 例如,打印带有行号的行
    9. print(f"{line_number}: {line.strip()}")
    10. def process_large_file(input_file_path, output_file_path):
    11. encoding = detect_encoding(input_file_path)
    12. print(f"检测到的编码: {encoding}")
    13. with open(input_file_path, "r", encoding=encoding) as input_file, open(output_file_path, "wb") as output_file:
    14. for line_number, line in enumerate(input_file, start=1):
    15. # 使用占位符函数处理每一行
    16. process_line_with_line_number(line, line_number)
    17. # 将处理后的行写入输出文件
    18. output_file.write(f"{line_number}: {line}\n".encode(encoding))
    19. if __name__ == "__main__":
    20. input_file_path = "input_large_file.txt"
    21. output_file_path = "output_large_file.txt"
    22. process_large_file(input_file_path, output_file_path)

     当处理大型文本文件时,为了降低内存的使用,可以使用生成器(generator)来逐行读取文件。生成器允许你逐步获取文件的每一行,而不是一次性将整个文件加载到内存中。以下是一个使用生成器逐行读取大型文本文件的例子:

    1. import chardet
    2. def detect_encoding(file_path):
    3. with open(file_path, 'rb') as f:
    4. result = chardet.detect(f.read())
    5. return result['encoding']
    6. def read_large_text_file(file_path):
    7. encoding = detect_encoding(file_path)
    8. print(f"检测到的编码: {encoding}")
    9. with open(file_path, 'r', encoding=encoding) as file:
    10. for line_number, line in enumerate(file, start=1):
    11. yield line_number, line
    12. if __name__ == "__main__":
    13. input_file_path = "large_text_file.txt"
    14. # 使用生成器逐行读取大型文本文件
    15. line_generator = read_large_text_file(input_file_path)
    16. # 处理每一行,例如打印行号和内容
    17. for line_number, line in line_generator:
    18. print(f"Line {line_number}: {line.strip()}")

  • 相关阅读:
    Pythony应用(02)-文字识别训练tesseract-ocr4
    制作一个模板
    java计算机毕业设计健康生活网站源程序+mysql+系统+lw文档+远程调试
    C++ Reference: Standard C++ Library reference: C Library: cstring: memcpy
    【测试】使用卷积神经网络(CNN)中的 卷积核 对 图像进行特征提取
    vue制作自己的组件库(仿ElementUI)
    MySQL数据库 前言
    MySQL表结构设计规范
    关于博图17安装体验过程—博图17安装失败原因(STEP7 许可证找不到)
    git撤销未git commit的文件
  • 原文地址:https://blog.csdn.net/book_dw5189/article/details/134473238