Home  >  Article  >  Backend Development  >  编写简单的Python程序来判断文本的语种

编写简单的Python程序来判断文本的语种

WBOY
WBOYOriginal
2016-06-06 11:24:181752browse

1.问题的描述

用Python进行文本处理时,有时候处理的文本中包含中文、英文、日文等多个语系的文本,有时候不能同时进行处理,这个时候就需要判别当前文本是属于哪个语系的。Python中有个langid工具包提供了此功能,langid目前支持97种语言的检测,非常好用。


2.程序的代码

以下Python是调用langid工具包来对文本进行语言检测与判别的程序代码:
 

import langid                             #引入langid模块 
  
def translate(inputFile, outputFile): 
  fin = open(inputFile, 'r')                  #以读的方式打开输入文件 
  fout = open(outputFile, 'w')                 #以写的方式打开输出文件 
  
  for eachLine in fin:                     #依次读入每一行 
    line = eachLine.strip().decode('utf-8', 'ignore')   #去除每行的首位空格等,并统一转化成Unicode 
    lineTuple = langid.classify(line)           #调用langid来对该行进行语言检测 
    if lineTuple[0] == "zh":               #如果该行语言大部分为中文,则不进行任何处理 
      continue 
  
    outstr = line                     #如果该行语言为非中文,则准备输出 
    fout.write(outstr.strip().encode('utf-8') + '\n')   #输出非中文的行,从Unicode转化成utf-8输出 
  
  fin.close() 
  fout.close() 
  
if __name__ == '__main__':                      #相当于main函数 
  translate("myInputFile.txt", "myOutputFile.txt") 
 

 以上代码是用来处理一个文本,将不属于中文的行依次输出到一个新的文件。

 
3.注意

第9、10行代码,langid.classify(line)的输出结果是一个二元组,二元组的第一项表示该文本所属的语系,如:zh表示中文、en表示英语、等等;二元组的第二项表示该文本中属于第一项中语系的所占比例。

 

希望对大家有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn