保留文本文件中指定字符串前面的所有文本(Python)


class ObstetricsText:

    @staticmethod
    def __removeAfterI__(key_text, read_path, save_path):
        """
        # remove text after key_text, including key_text.
        :return:
        """
        list_result = []
        file = open(read_path, encoding="UTF-8")
        for line in file.readlines():
            index = line.find(key_text)
            if index > 0:
                list_result.append(line[0: index])
            else:
                list_result.append(line.replace("\n", ""))
        file2 = open(save_path, 'w', encoding="UTF-8")
        for line in list_result:
            file2.write(line + "\n")
        file.close()
        file2.close()
        print("remove success!")
        print("File path saved is ", save_file)


if __name__ == '__main__':
    read_file = r"C:\Users\Administrator\Desktop\最近工作\实验数据\标准\特征文本后10886.txt"
    save_file = r"C:\Users\Administrator\Desktop\最近工作\实验数据\标准\特征文本后10886_20180501.txt"
    ObstetricsText.__removeAfterI__("诊断:", read_file, save_file)

可能遇到的问题:

  • 编码问题
    读取或写入文件可能出现乱码,所以设置好文件编码格式
  • 换行符问题
    读取或写入文件时请谨慎处理换行符\n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值