文本预处理1--去除#和句号之间内容

1.针对文本里特定两个符号之间内容的中文进行去除,本次选取#和句号之间的内容进行去除。

2.大家可以根据自己的实际需求修改代码实现自己的文本内容的整理。

3.下面是去除#和句号之间内容的python代码:其中读取的是txt文本,处理后的内容写回原txt文件。

import os
def remove_content_between_hash_and_period(input_text):
    start_search_pos = 0
    while True:
        hash_pos = input_text.find('#', start_search_pos)
        if hash_pos == -1:
            break
        period_pos = input_text.find('。', hash_pos)
        if period_pos == -1:
            input_text = input_text[:hash_pos]
            break
        input_text = input_text[:hash_pos] + input_text[period_pos + 1:]
        start_search_pos = hash_pos
    return input_text


def process_txt_files(folder_path):
    for filename in os.listdir(folder_path):
        if filename.endswith('.txt'):
            file_path = os.path.join(folder_path, filename)
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                processed_content = remove_content_between_hash_and_period(content)

            # 可选:将处理后的内容写回文件
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(processed_content)

            # 打印处理后的内容(如果需要)
            # print(f'Processed content of {filename}:')
            # print(processed_content)


# 替换为你的文件夹路径
folder_path = "C:\\Users\\lenovo\\Desktop"
process_txt_files(folder_path)

 

 

 

 

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值