Python查找文件中包含中文的行

前言

近几天在做多语言版本的时候再次发现,区分各种语言真的是一件比较困难的事情,上一次做中文提取工具的就花了不少时间,这次决定用python试一试,结果写起来发现真是方便不少,自己整理了一下方便以后查找使用。

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# find the line of containing chinese in files

__author__ = 'AlbertS'

import re

def start_find_chinese():
    find_count = 0;
    with open('ko_untranslated.txt', 'wb') as outfile:
        with open('source_ko.txt', 'rb') as infile:
            while True:
                content = infile.readline()
                if re.match(r'(.*[\u4E00-\u9FA5]+)|([\u4E00-\u9FA5]+.*)', content.decode('utf-8')):
                    outfile.write(content)
                    find_count += 1;

                if not content:
                    return find_count

# start to find
if __name__ == '__main__':
    count = start_find_chinese()
    print("find complete! count =", count)

原始文件

source_ko.txt文件内容

3   캐릭터 Lv.50 달성
8   캐릭터 Lv.80 달성
10  캐릭터 Lv.90 달성
...
...
2840    飞黄腾达
4841    同归于尽
8848    캐릭터 Lv.50 달

运行效果(ko_untranslated.txt文件)

2840    飞黄腾达
4841    同归于尽

总结

  1. 其实这段小小的代码中包含了两个常用的功能,那就是读写文件和正则表达式。
  2. 这也是两个重要的知识点,其中with操作可能防止资源泄漏,操作起来更加方便。
  3. 正则表达式可是一个文字处理的利器,代码中的正则可能还不太完善,后续我会继续补充更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AlbertS

常来“玩”啊~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值