Python: 分块读取文本文件

news/2024/10/18 18:22:12/

在处理大文件时,逐行或分块读取文件是很常见的需求。下面是几种常见的方法,用于在 Python 中分块读取文本文件:

在这里插入图片描述

1、问题背景

如何分块读取一个较大的文本文件,并提取出特定的信息?

  • 问题描述:

    python">f=open('blank.txt','r')
    quotes=f.read()
    noquotes=quotes.replace('"','')
    f.close()rf=open('blank.txt','w')
    rf.write(noquotes)
    rf.close()   f=open('blank.txt','r')
    finished = False
    postag=[]
    while not finished:line=f.readline()words=line.split()postag.append(words[4])postag.append(words[6])postag.append(words[8])              finished=True
    
    • 使用 open()函数打开文件,将文件内容读入变量 quotes,然后用 replace()函数去除所有双引号,再将处理后的内容写回文件。
    • 再次打开文件,并使用 readline() 函数逐行读取文件内容。
    • 对于每一行,将其按空格分割成一个列表 words,并提取出列表中的第 5、7 和 9 个元素,将其添加到 postag 列表中。
  • 问题原因:

    • 问题在于 while not finished: 循环仅迭代了文件的第一行,因此无法处理整个文件。

2、解决方案

  • 使用 xml.etree.ElementTree 模块解析 XML 文件:

    python">from xml.etree import ElementTreeline = '<word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head="7" relation="ADV"/>'element = ElementTree.fromstring(line)form = element.attrib['form']
    lemma = element.attrib['lemma']
    postag = element.attrib['postag']print(form, lemma, postag)
    
    • 使用 ElementTree.fromstring() 方法将 XML 字符串解析成一个元素对象。
    • 使用 element.attrib 获取元素的属性,并提取出 formlemmapostag 属性的值。
    • 打印出提取出的信息。
  • 使用正则表达式提取信息:

    python">import redata = open('x').read()
    RE = re.compile('.*form="(.*)" lemma="(.*)" postag="(.*?)"', re.M)
    matches = RE.findall(data)
    for m in matches:print(m)
    
    • 使用 re.compile() 方法编译正则表达式,并将其应用到文本数据中。
    • 使用 findall() 方法查找所有匹配正则表达式的子字符串,并将其存储在 matches 列表中。
    • 遍历 matches 列表,并打印出每个匹配子字符串。
  • 使用 SAX 解析器解析 XML 文件:

    python">import xml.saxclass Handler(xml.sax.ContentHandler):def startElement(self, tag, attrs):if tag == 'word':print('form=', attrs['form'])print('lemma=', attrs['lemma'])print('postag=', attrs['postag'])ch = Handler()
    f = open('myfile')
    xml.sax.parse(f, ch)
    
    • 定义一个 SAX 解析器类 Handler,并重写 startElement() 方法,用于处理 XML 文件中的元素。
    • 使用 xml.sax.parse() 方法解析 XML 文件,并指定解析器对象 ch
    • 每次遇到一个 word 元素,就会调用 startElement() 方法,并打印出元素的 formlemmapostag 属性的值。
  • 使用 BeautifulSoup 解析 XML 文件:

    python">from bs4 import BeautifulSoupsoup = BeautifulSoup(open('myfile').read(), 'xml')for word in soup.find_all('word'):print('form=', word['form'])print('lemma=', word['lemma'])print('postag=', word['postag'])
    
    • 使用 BeautifulSoup() 方法解析 XML 文件,并将其存储在 soup 对象中。
    • 使用 find_all() 方法查找所有 word 元素,并将其存储在 words 列表中。
    • 遍历 words 列表,并打印出每个元素的 formlemmapostag 属性的值。

选择方法

  • 如果需要逐行处理文件,选择方法1。
  • 如果需要分块处理二进制文件或大文本文件,选择方法2。
  • 如果需要按行块处理文件,选择方法3。
  • 如果需要处理大规模的 CSV 文件,选择方法4。

每种方法都有其特定的应用场景,可以根据具体需求选择合适的方法。


http://www.ppmy.cn/news/1474451.html

相关文章

mupdf加载PDF显示中文乱码

现象 加载PDF显示乱码,提示非嵌入字体 non-embedded font using identity encoding调式 在pdf-font.c中加载字体 调试源码发现pdf文档的字体名字居然是GBK&#xff0c;估计又是哪个windows下写的pdf生成工具生成pdf 字体方法&#xff1a; static pdf_font_desc * load_cid…

echarts使用自定义图形实现3D柱状图

先看下效果吧 实现思路 使用graphic创建并注册自定义图形。根据每组的数据值&#xff0c;得到一个对应的点&#xff0c;从点出发用canvas绘制一组图形&#xff0c;分别为 顶部的菱形 const CubeTop echarts.graphic.extendShape({buildPath: function (ctx, shape) {const c1…

bqplot教程:在Jupyter Notebook中进行交互式数据可视化

文章目录 介绍1.1 数据可视化的重要性1.2 bqplot库的概述安装和快速入门 安装和导入2.1 安装bqplot使用pip安装使用conda安装 2.2 导入必要的库示例&#xff1a;导入并使用bqplot创建简单图表 数据集准备3.1 导入数据集使用 pandas 导入 CSV 文件使用 pandas 导入其他格式的数据…

ubuntu系统下使用gelsight

一、背景 创建 conda create -n gelsight python3.8 conda activate gelsight cd GelSight/gsrobotics-main/demos/marker_tracking/ python3 mean_shift_marker_tracking.py ModuleNotFoundError: No module named ‘numpy’ pip3 install numpy ModuleNotFoundError: N…

2024机器遗忘(Machine Unlearning)技术分类-思维导图

1 介绍 机器遗忘&#xff08;Machine Unlearning&#xff09;是指从机器学习模型中安全地移除或"遗忘"特定的数据点或信息。这个概念源于数据隐私保护的需求&#xff0c;尤其是在欧盟通用数据保护条例&#xff08;GDPR&#xff09;等法规中提出的"被遗忘的权利…

Rust开发环境搭建

Rust开发环境搭建 环境 rust: 1.79.0(2024-06-13)1. Rustup下载器在线安装 windows&#xff1a; https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe unix&#xff1a; curl --proto https --tlsv1.2 -sSf https://sh.rustup.rs | sh2. R…

【NLP学习笔记】transformers中的tokenizer切词时是否返回token_type_ids

结论 先说结论&#xff1a; 是否返回token_type_ids&#xff0c;可以在切词时通过 return_token_type_idsTrue/False指定&#xff0c;指定了True就肯定会返回&#xff0c;指定False&#xff0c;不一定就不返回。 分析 Doc地址 https://huggingface.co/docs/transformers/main…

已解决 javax.xml.transform.TransformerFactoryConfigurationError 异常的正确解决方法,亲测有效!!!

已解决 javax.xml.transform.TransformerFactoryConfigurationError 异常的正确解决方法&#xff0c;亲测有效&#xff01;&#xff01;&#xff01; 目录 一、问题分析 二、报错原因 三、解决思路 四、解决方法 五、总结 博主v&#xff1a;XiaoMing_Java 博主v&#x…