8个txt自动化脚本,一定有你用得上的!Python如何读取txt文件数据!

news2024/9/23 19:26:37

在这里插入图片描述

这次和大家分享txt办公自动化,包括读取、对比、过滤、合并、转换格式、提取数据、统计词频、生成报告等。

分享一份Python学习大礼包(激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程)[点击领取,100%免费!]


准备工作:安装所需的Python库

  • re(正则表达式操作,用于复杂文本匹配)
  • csv(处理CSV文件)
  • json(处理JSON文件)
  • collections(用于统计词频)
  • matplotlibwordcloud(生成词云图)

1.读取txt内容

1.1. 逐行读取txt文件
  • 在数据处理的第一步就是读取txt文件。以下是逐行读取txt文件的示例代码:
def read_txt_file_by_line(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            print(line.strip())

# 示例调用
read_txt_file_by_line('example.txt')
1.2. 读入整个txt文件内容
  • 如果需要将整个txt文件的内容读入到一个字符串中,可以使用以下代码:
def read_txt_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

# 示例调用
content = read_txt_file('example.txt')
print(content)

2.对比两个txt文件内容

2.1. 基本文本对比
  • 有时候我们需要比较两个txt文件内容是否相同,以下代码可以实现这一功能:
def compare_txt_files(file1, file2):
    with open(file1, 'r', encoding='utf-8') as f1, open(file2, 'r', encoding='utf-8') as f2:
        content1 = f1.readlines()
        content2 = f2.readlines()
    
    for line1, line2 in zip(content1, content2):
        if line1 != line2:
            print(f'Difference found:\nFile1: {line1}\nFile2: {line2}')

# 示例调用
compare_txt_files('file1.txt', 'file2.txt')
2.2. 差异高亮显示
  • 为了更直观地显示txt文件之间的差异,可以用差异高亮显示的方法。我们使用"difflib"库来实现:
import difflib

def highlight_differences(file1, file2):
    with open(file1, 'r', encoding='utf-8') as f1, open(file2, 'r', encoding='utf-8') as f2:
        content1 = f1.readlines()
        content2 = f2.readlines()

    diff = difflib.unified_diff(content1, content2, fromfile='file1', tofile='file2')
    for line in diff:
        print(line)

# 示例调用
highlight_differences('file1.txt', 'file2.txt')  

3.txt文件内容过滤

3.1. 过滤特定关键字行
  • 在处理txt文件时,可能需要过滤掉包含特定关键字的行。以下是一个示例代码:
def filter_lines_by_keyword(filepath, keyword):
    with open(filepath, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    
    filtered_lines = [line for line in lines if keyword not in line]
    return filtered_lines

# 示例调用
filtered = filter_lines_by_keyword('example.txt', 'filter_keyword')
for line in filtered:
    print(line.strip())
3.2. 过滤空行和注释行
  • 有时候需要过滤掉空行和注释行(比如以#开头的行)。以下是实现这一功能的代码:
def filter_empty_and_comment_lines(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    
    filtered_lines = [line for line in lines if line.strip() and not line.strip().startswith('#')]
    return filtered_lines

# 示例调用
filtered = filter_empty_and_comment_lines('example.txt')
for line in filtered:
    print(line.strip())

4.合并多个txt文件

4.1. 简单合并
  • 将多个txt文件的内容简单合并成一个文件,可以使用以下代码:
def merge_txt_files(file_list, output_file):
    with open(output_file, 'w', encoding='utf-8') as outfile:
        for file in file_list:
            with open(file, 'r', encoding='utf-8') as infile:
                outfile.write(infile.read())
                outfile.write('\n')

# 示例调用
merge_txt_files(['file1.txt', 'file2.txt', 'file3.txt'], 'merged.txt')
4.2. 按行混合合并
  • 如果需要按行混合合并多个文件的内容,可以使用以下代码:
def merge_files_by_line(file_list, output_file):
    files = [open(file, 'r', encoding='utf-8') for file in file_list]
    with open(output_file, 'w', encoding='utf-8') as outfile:
        while True:
            lines = [file.readline() for file in files]
            if all(line == '' for line in lines):
                break
            for line in lines:
                if line:
                    outfile.write(line.strip() + '\n')
    for file in files:
        file.close()

# 示例调用
merge_files_by_line(['file1.txt', 'file2.txt', 'file3.txt'], 'merged_by_line.txt')

5.将txt文件转换为其他格式

5.1. 转换为csv格式
  • 有时候我们需要将txt文件的内容转换成csv格式以便进行数据处理或分析,下面是相关代码示例:
import csv

def txt_to_csv(txt_file, csv_file):
    with open(txt_file, 'r', encoding='utf-8') as infile, open(csv_file, 'w', newline='', encoding='utf-8') as outfile:
        writer = csv.writer(outfile)
        for line in infile:
            writer.writerow(line.strip().split())

# 示例调用
txt_to_csv('example.txt', 'output.csv')
这段代码将txt文件的内容逐行读取,并按空格或制表符拆分成csv格式。
5.2. 转换为json格式
  • 除了csv格式,JSON格式也是常用的数据存储格式。以下是将txt文件转换为JSON格式的代码示例:
import json

def txt_to_json(txt_file, json_file):
    data = []
    with open(txt_file, 'r', encoding='utf-8') as infile:
        for line in infile:
            data.append(line.strip())

    with open(json_file, 'w', encoding='utf-8') as outfile:
        json.dump(data, outfile, indent=4)

# 示例调用
txt_to_json('example.txt', 'output.json')
这段代码将txt文件的每一行内容作为JSON数组里的一个元素进行存储。

6.从txt文件提取数据

6.1. 提取特定模式的文本
  • 有时候我们需要从txt文件中提取符合特定模式的文本,可以使用正则表达式(re库)来实现。以下代码示例演示如何提取符合某个模式的文本:
import re

def extract_pattern_from_txt(pattern, txt_file):
    matches = []
    with open(txt_file, 'r', encoding='utf-8') as file:
        content = file.read()
        matches = re.findall(pattern, content)
    return matches

# 示例调用,提取所有的数字
pattern = r'\d+'
matches = extract_pattern_from_txt(pattern, 'example.txt')
print("Match found:", matches)
6.2. 提取邮件地址或URL
  • 我们可以使用类似的方法来提取邮件地址或URL:
def extract_emails_and_urls(txt_file):
    email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
    url_pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    
    with open(txt_file, 'r', encoding='utf-8') as file:
        content = file.read()
        
    emails = re.findall(email_pattern, content)
    urls = re.findall(url_pattern, content)
    
    return emails, urls

# 示例调用
emails, urls = extract_emails_and_urls('example.txt')
print("Emails found:", emails)
print("URLs found:", urls)

7.统计txt文件中的词频

7.1. 统计单词出现次数
  • 我们可以统计txt文件中单词的出现频次,并对其进行排序。以下代码示例展示如何实现:
from collections import Counter

def count_word_frequency(txt_file):
    with open(txt_file, 'r', encoding='utf-8') as file:
        words = file.read().split()
        word_freq = Counter(words)
    return word_freq

# 示例调用
word_freq = count_word_frequency('example.txt')
for word, freq in word_freq.most_common():
    print(f'{word}: {freq}')
7.2. 生成词云图
  • 对于可视化效果,可以生成词云图来显示词频分布:
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def generate_word_cloud(txt_file):
    with open(txt_file, 'r', encoding='utf-8') as file:
        text = file.read()
        
    wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()

# 示例调用
generate_word_cloud('example.txt')

8.自动生成txt报告

8.1. 从模板生成报告
  • 可以使用txt模板生成报告,将动态数据填充到模板中。以下示例展示如何从模板生成报告:
def generate_report_from_template(template_file, output_file, data):
    with open(template_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
        content = infile.read()
        for key, value in data.items():
            content = content.replace(f'{{{{ {key} }}}}', str(value))
        outfile.write(content)

# 示例调用
data = {
    'name': 'Alice',
    'date': '2024-08-17',
    'summary': 'This is a summary of the report.'
}
generate_report_from_template('template.txt', 'report.txt', data)
8.2. 动态生成报告内容
  • 有时候需要动态生成报告的内容,以下示例展示如何实现:
def generate_dynamic_report(output_file, sections):
    with open(output_file, 'w', encoding='utf-8') as outfile:
        for section in sections:
            outfile.write(f'# {section["title"]}\n\n')
            outfile.write(f'{section["content"]}\n\n')

# 示例调用
sections = [
    {
        "title": "Introduction",
        "content": "This is the introduction section of the report."
    },
    {
        "title": "Data Analysis",
        "content": "This section contains the analysis of the data."
    }
]
generate_dynamic_report('dynamic_report.txt', sections)

图片

总结

  • 最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利

  • 最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。

包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】领取!

  • ① Python所有方向的学习路线图,清楚各个方向要学什么东西
  • ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
  • ③ 100多个Python实战案例,学习不再是只会理论
  • ④ 华为出品独家Python漫画教程,手机也能学习

可以扫描下方二维码领取【保证100%免费

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2110799.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

GAMES101(0~1作业)

搭建虚拟机环境 安装Oracle VM VirtualBox虚拟机,安装虚拟硬盘,配置Linux Ubuntu-64 bit系统,启动虚拟机,发生冲突错误: 将Vmware虚拟设备取消挂起状态,关机确保 Hyper-V 完全关闭:bcdedit /se…

Pandas DataFrame的多级列索引导出到Excel时,如何避免空白行和列

我想将multi-header数据框保存为Excel文件。以下是示例代码: import pandas as pd import numpy as npheader pd.MultiIndex.from_product([[location1,location2],[S1,S2,S3]],names[loc,S])df pd.DataFrame(np.random.randn(5, 6), index[a,b,c,d,e], columnsh…

Python 中的 11 种经典时间序列预测方法(备忘单)

摘要: 本文演示了 11 种不同的经典时间序列预测方法,这些方法包括: 自回归(AR) 移动平均线 (MA) 自回归移动平均线 (ARMA) 自回归综合移动平均线 (ARIMA) 季节性自回归综合移动平均线 (SARIMA) 季节性自回归综合移动平均线与外生回归量... 本文演示了 11 种不同的经典时间序…

sheng的学习笔记-AI-半监督聚类

AI目录:sheng的学习笔记-AI目录-CSDN博客 半监督学习:sheng的学习笔记-AI-半监督学习-CSDN博客 聚类:sheng的学习笔记-AI-聚类(Clustering)-CSDN博客 均值算法:sheng的学习笔记-AI-K均值算法_k均值算法怎么算迭代两次后的最大…

掌握Git分支管理策略:让团队协作更高效

在现代软件开发过程中,版本控制系统(VCS)是不可或缺的一部分。Git作为目前最流行的分布式版本控制系统之一,为开发者提供了强大的工具集来管理代码变更历史。然而,仅仅掌握Git的基本命令并不足以应对大型项目和团队协作…

当天审稿,当天上线,9月检索!

各领域CNKI知网普刊,最快一期预计下周送检,最快1天上线 领域广,计算机,社科,医学等各个方向都能收 包检索,可提供期刊部发票 知名出版社英文普刊 NO.1、Food Science and Nutrition Studies ISSN: 2573…

2024年全国大学生数学建模C题论文

C 题 农作物的种植策略 问题 1 :2024-2030 年农作物的最优种植方案 1.1 问题 1 的第一小问详细 该问题要求在假设未来农作物的预期销售量、种植成本、亩产量和销售价 格稳定的情况下,为乡村制定从 2024 年到 2030 年的农作物最优种植方案。特 别是要考虑…

骨传导耳机哪个牌子好用?精选五款黄金畅销骨传导机型测评

随着消费者对健康聆听方式的日益重视,骨传导耳机的市场需求持续高涨。众多耳机厂商在耳机的外观设计上倾注了大量心血,但在此过程中,部分品牌却忽视了产品的核心音质与佩戴舒适度,导致市场上涌现出一些外观时尚但内在品质不尽如人…

缓解父母焦虑!详细实测!这些免费AI可以成为孩子提高学习能力的得力助手!

近日,新版三年级英语教材冲上了热搜。家长纷纷表示,新版教材连26个英文字母都不教了,直接进入单词和文章教学。 ”娃都零基础,开学怎么跟得上?“ “这不是卷孩子,这是卷家长啊!” 不仅是英语&…

【爱加密_云平台-注册/登录安全分析报告】

前言 由于网站注册入口容易被黑客攻击,存在如下安全问题: 暴力破解密码,造成用户信息泄露短信盗刷的安全问题,影响业务及导致用户投诉带来经济损失,尤其是后付费客户,风险巨大,造成亏损无底洞…

[已更新问题二三matlab+python]2024数学建模国赛高教社杯C题:农作物的种植策略 思路代码文章助攻手把手保姆级

发布于9.6 10:00 有问题后续会修正!! 问题一代码展示: 问题二代码结果展示: 问题三代码展示: https://docs.qq.com/doc/DVVVlV0NmcnBDTlVJ问题一部分代码分享: #!/usr/bin/env python # coding: utf-8# In[15]:import pandas as pd# In[16]:# 读取Excel文件 file_path 附件2…

platform框架

platform框架 注册设备进入总线platform_device_register函数 注册驱动进入总线platform_driver_register函数 注册设备进入总线 platform_device_register函数 int platform_device_register(struct platform_device *pdev) struct platform_device {const char * name; 名…

《Rust避坑式入门》第2章:解决多线程并发数据竞争的不可变性

从第1章所讨论的出现数据竞争问题的多线程并发剧院订票系统的代码能够看出,虽然可变性能够方便地随时修改值,但滥用可变性,会在多线程并发编程时,带来数据竞争的难题。 共享可变状态所带来的多线程并发时的数据竞争难题&#xff…

维度不固定的多维数组形参笔记

在利用多维数组作为函数形参时遇到了点问题,如: void fun(char str[][10]); 这个函数可以传入多维数组,但元素个数必须是固定的,假如传入一个str[][20],元素个数不一样的数组,那么这个函数就不适用了&…

6.2排序——选择排序与堆排序

本篇博客梳理选择排序,包括直接选择排序与堆排序 排序全部默认排成升序 一、直接选择排序 1.算法思想 每次遍历都选出最小的和最大的,放到序列最前面/最后面 2.具体操作 (1)单趟 每次遍历都选出最小的…

Opencv中的直方图(1)计算反向投影直方图函数calcBackProject()的使用

操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 计算直方图的反向投影。 cv::calcBackProject 函数计算直方图的反向投影。也就是说,类似于 calcHist,在每个位置 (x, y)…

主流的3D模型格式有什么区别?

主流的3D模型格式在多个方面存在区别,这些区别主要体现在格式的特点、支持的功能、使用场景以及兼容性等方面。51建模网支持持obj、fbx、stl、glb、gltf、dae、3ds模型格式上传展示。以下是对几种主流3D模型格式的区别进行的详细分析: 1. OBJ格式 特点&…

初始JESD204B高速接口协议(JESD204B一)

本文参考 B B B站尤老师 J E S D 204 B JESD204B JESD204B视频,图片来自 J E S D JESD JESD手册或者 A D I / T I ADI/TI ADI/TI官方文档。 1、对比 L V D S LVDS LVDS与 J E S D 204 JESD204 JESD204 J E S D 204 B JESD204B JESD204B是逻辑器件和高速 A D C / D …

【YashanDB知识库】修改字段长度后,jdbc驱动接口报YAS-04007 Message:result set metadata changed异常

问题现象 yashandb修改表的字段长度后,客户的业务接口报YAS-04007异常,截图如下: 问题的风险及影响 客户的业务在访问yashandb时异常出错,影响使用 问题影响的版本 所有的yashandb版本 问题发生原因 使用jdbc接口获取PreparedStatement…

库存盘点频出错?试试这款专业软件的库存分析报表工具

在企业的日常运营中,库存管理的实际操作直接影响到我们的工作效率和企业的整体盈利情况。库存不仅是企业的物资储备,更是我们每天工作中必须处理的关键环节。如果库存管理不到位,可能会导致产品积压、资金占用,甚至影响到销售和客…