Python世界:文本操作之日记模板生成实践

Python世界:文本操作之日记模板生成实践

背景任务


写一个脚本自动逆序处理随记笔记,并在数字后自动添加,日期等固定格式,方便整理。

比如,输入信息:1115,并逆序处理,输出转换成:2024-11-15:周X。

实现思路


咱先用AI大模型尝试实现下,于是写了以下prompt:

请用python实现一下功能,并给出参考代码:将倒序固定格式的文本逆序处理,全部转化为TXT文本格式。

具体实现思路:

  • 输入原始txt,输出改变后的txt
  • 遍历所有文本行
  • 找到纯数字行标识,并存储
  • 按数字行分段切割文本数据,逆序
    • 将数字行替换为指定年月日格式。并查询对应星期几,比如周一。
    • 跟附【今日事】模板
    • 跟附原本行间字符串(顺序写)

Copilot辅助编码

好的,我明白你的需求。以下是一个Python代码示例,展示了如何实现你描述的功能:

import datetime

def reverse_text(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 存储分段的文本
    sections = []
    current_section = []

    for line in lines:
        if line.strip().isdigit():
            if current_section:
                sections.append(current_section)
                current_section = []
            current_section.append(line.strip())
        else:
            current_section.append(line.strip())
    
    if current_section:
        sections.append(current_section)

    # 逆序处理每个分段
    reversed_sections = []
    for section in sections:
        date_str = section[0]
        date_obj = datetime.datetime.strptime(date_str, '%Y%m%d')
        formatted_date = date_obj.strftime('%Y年%m月%d日')
        weekday = date_obj.strftime('%A')
        today_event = f"【今日事】{formatted_date} {weekday}"

        reversed_section = [today_event] + section[1:]
        reversed_sections.append(reversed_section)

    # 将处理后的文本写入输出文件
    with open(output_file, 'w', encoding='utf-8') as file:
        for section in reversed(reversed_sections):
            for line in section:
                file.write(line + '\n')

# 示例用法
input_file = 'input.txt'
output_file = 'output.txt'
reverse_text(input_file, output_file)

代码说明:

  1. 读取输入文件:读取原始文本文件的所有行。
  2. 分段处理:根据纯数字行(假设为日期)分段存储文本。
  3. 逆序处理:对每个分段进行逆序处理,并将日期行转换为指定格式,附加【今日事】模板。
  4. 写入输出文件:将处理后的文本写入新的输出文件。

你可以根据需要调整日期格式和模板内容。如果有任何问题或需要进一步的帮助,请随时告诉我!

源: 与 Copilot 的对话,
(1) 【Python基础】字符串逆序(反转)输出的几种方式实例. https://blog.youkuaiyun.com/dyfDewey/article/details/107000800.
(2) python实现字符串逆序的算法-优快云博客. https://blog.youkuaiyun.com/licy__/article/details/143844919.
(3) 如何使用python 作出字符串逆序 | PingCode智库. https://bing.com/search?q=python+%e5%ae%9e%e7%8e%b0%e6%96%87%e6%9c%ac%e9%80%86%e5%ba%8f%e5%a4%84%e7%90%86.
(4) Python字符串逆序输出的三种方法(python中字符串逆序输出 … https://python.zaixianjisuan.com/zifu/pythonzi-fu-chuan-ni-xu-shu-chu-de-san-zhong-fang-fa.html.
(5) 如何使用python 作出字符串逆序 | PingCode智库. https://docs.pingcode.com/baike/1150030.
(6) Python字符串逆序:轻松掌握多种实现方法. https://python.zaixianjisuan.com/zifu/pythonzi-fu-chuan-ni-xu-qing-song-zhang-wo-duo-zhong-shi-xian-fang-fa6.html.

尝试过无法直接使用,运行会报错。

可使用版本

主要修改点:

  • 增加正则查找,通配符:^\d\d\d\d$,表征以数字开头以数字结束,且仅有4个数字。
  • 修改了日期转换
  • 修改了固定文本模板

代码如下:

# -*- coding: utf-8 -*-

import datetime
import re

week_days_en = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
week_days_cn = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]

def reverse_text(input_file, output_file, re_time_pattern):
    with open(input_file, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 存储分段的文本
    sections = []
    section_id = []
    
    years = '2024'
    concate_sym = '-'
    out_line_today_pattern = '''\
【今日事】
- A
- B
  '''

    i = 0
    for line in lines:
        i += 1
        line_str = line.strip()
        if re.match(re_time_pattern, line_str) and len(line_str) == 4:
            month = line_str[0:2]
            day = line_str[2:4]
            line_str_time = years + concate_sym + month + concate_sym + day + ': '
            date = datetime.date(int(years), int(month), int(day))
            day_of_week = date.weekday()
            day_name = week_days_cn[day_of_week]
            line_str_cur = line_str_time + day_name + "。"
            sections.append(line_str_cur)
            section_id.append(i)

    sections_reverse = sections[::-1]
    section_id_reverse = section_id[::-1]


    # 将处理后的文本写入输出文件
    with open(output_file, 'w', encoding='utf-8') as file:
        i = 0
        for line_id in section_id_reverse:
            out_line_date = sections_reverse[i]
            out_line_today = out_line_today_pattern
            if i == 0:
                out_line_txt = lines[line_id:]
                out_line_txt.append('\n') # 最后段落的换行符
            else:
                out_line_txt = lines[line_id:section_id_reverse[i-1]-1]
            i += 1
            file.write(out_line_date + '\n')
            file.write(out_line_today + '\n')
            file.write(''.join(out_line_txt)) # 将list合并为str


# 示例用法
input_file = 'input.txt'
output_file = 'output.txt'
re_time_pattern = '^\d\d\d\d$'
reverse_text(input_file, output_file, re_time_pattern)

测试用例


用例输入:

1125
xx
nishuo还能不能?

辛苦您

【发送方市】
1124

发现 ;就

这个测试
1123
小分队
看依稀a

【主体1】信息和熵
1122
想学习

信息和熵

测试一下

参考输出:

2024-11-22: 周五。
【今日事】

  • A
  • B

想学习

信息和熵

测试一下
2024-11-23: 周六。
【今日事】

  • A
  • B

小分队
看依稀a

【主体1】信息和熵
2024-11-24: 周日。
【今日事】

  • A
  • B

发现 ;就

这个测试
2024-11-25: 周一。
【今日事】

  • A
  • B

xx
nishuo还能不能?

辛苦您

【发送方市】

本文小结


本文通过实现一个逆序处理文本的demo,练习了Python正则查找、文本读取写入、字符串等操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值