前言
近幾天在做多語言版本的時候再次發現,區分各種語言真的是一件比較困難的事情,上一次做中文提取工具的就花了不少時間,這次決定用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 = ;
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 += ;
if not content:
return find_count
# start to find
if __name__ == '__main__':
count = start_find_chinese()
print("find complete! count =", count)
原始檔案
source_ko.txt檔案内容
캐릭터 Lv.50 달성
캐릭터 Lv.80 달성
캐릭터 Lv.90 달성
...
...
飛黃騰達
同歸于盡
캐릭터 Lv.50 달
運作效果(ko_untranslated.txt檔案)
2840 飛黃騰達
4841 同歸于盡
總結
- 其實這段小小的代碼中包含了兩個常用的功能,那就是讀寫檔案和正規表達式。
- 這也是兩個重要的知識點,其中with操作可能防止資源洩漏,操作起來更加友善。
- 正規表達式可是一個文字處理的利器,代碼中的正則可能還不太完善,後續我會繼續補充更新。