找回密码
 立即注册
搜索
热搜: 活动 交友 discuz

处理半边文档的PY,希望你喜欢。

[复制链接]
admin 发表于 3 天前 | 显示全部楼层 |阅读模式
import os

# 定义标点符号集
punctuation_set = set("。,、;:?!“”‘’()【】《》…—…")

def is_punctuation(char):
    """检查字符是否为标点符号"""
    return char in punctuation_set

def process_file(input_folder):
    # 遍历输入文件夹中的所有文件
    for filename in os.listdir(input_folder):
        if filename.endswith('.txt'):  # 只处理文本文件
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(input_folder, filename.replace('.txt', '_processed.txt'))

            with open(input_path, 'r', encoding='utf-8') as infile, \
                 open(output_path, 'w', encoding='utf-8') as outfile:

                content = infile.read()
                processed_content = []

                # 逐字符处理内容
                i = 0
                while i < len(content):
                    if content == '\n':
                        # 检查换行符前的字符是否为标点符号
                        j = i - 1
                        while j >= 0 and content[j] == ' ':  # 忽略换行符前的所有空格
                            j -= 1
                        if j >= 0 and is_punctuation(content[j]):
                            processed_content.append('\n')
                        else:
                            processed_content.append('')
                    else:
                        processed_content.append(content)
                    i += 1

                # 写入处理后的内容到新文件
                outfile.write(''.join(processed_content))

# 示例用法
input_folder = 'YY'
process_file(input_folder)

使用说明,下载文本文档,另存为后缀名PY。把半边文档放入YY文件夹中,点击PY即可处理完毕。PY文本文档可自由下载。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|文明与科学

GMT+8, 2024-9-19 09:57 , Processed in 0.159506 second(s), 14 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表