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

(编辑:jimmy 日期: 2024/9/29 浏览:2)

前言

近几天在做多语言版本的时候再次发现,区分各种语言真的是一件比较困难的事情,上一次做中文提取工具的就花了不少时间,这次决定用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 "htmlcode">
2840 飞黄腾达
4841 同归于尽

总结

1. 其实这段小小的代码中包含了两个常用的功能,那就是读写文件和正则表达式。

2. 这也是两个重要的知识点,其中with操作可能防止资源泄漏,操作起来更加方便。

3. 正则表达式可是一个文字处理的利器,代码中的正则可能还不太完善,后续我会继续补充更新。

以上这篇Python查找文件中包含中文的行方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。