当前位置: 移动技术网 > IT编程>脚本编程>Python > Python查找文件中包含中文的行方法

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

2019年01月04日  | 移动技术网IT编程  | 我要评论

什么叫亚健康,电梯突然坠20层,懒人100

前言

近几天在做多语言版本的时候再次发现,区分各种语言真的是一件比较困难的事情,上一次做中文提取工具的就花了不少时间,这次决定用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. 正则表达式可是一个文字处理的利器,代码中的正则可能还不太完善,后续我会继续补充更新。

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网