Python下的英文预处理

本文介绍了一种用于英文文本预处理的方法,包括文件读取、句子分割、内容清理、词性标注、分词、拼写检查、停用词去除、短词过滤及词干化等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 得到原始文本内容

  1. def FileRead(self,filePath):  
  2.     f = open(filePath)  
  3.     raw=f.read()  
  4.    return raw  

二 分割成句子

  1. def SenToken(self,raw):#分割成句子  
  2.     sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')  
  3.     sents = sent_tokenizer.tokenize(raw)  
  4.     return  sents  


三 句子内容的清理,去掉数字标点和非字母字符

  1. def CleanLines(self,line):  
  2.     identify = string.maketrans('''')  
  3.     delEStr = string.punctuation +string.digits  #ASCII 标点符号,数字    
  4.       cleanLine = line.translate(identify,delEStr) #去掉ASCII 标点符号和空格  
  5.     cleanLine =line.translate(identify,delEStr) #去掉ASCII 标点符号  
  6.    return cleanLine  

四nltk.pos_tag进行词性标注

  1. def POSTagger(self,sent):  
  2.     taggedLine=[nltk.pos_tag(sent) for sent in sents]  
  3.    return taggedLine  

五 nltk.word_tokenize分词

  1. def WordTokener(self,sent):#将单句字符串分割成词  
  2.         result=''  
  3.         wordsInStr = nltk.word_tokenize(sent)  
  4.        return wordsInStr  

六 enchant拼写检查

  1. def WordCheck(self,words):#拼写检查  
  2.     d = enchant.Dict("en_US")  
  3.     checkedWords=()  
  4.     for word in words:  
  5.         if not d.check(word):  
  6.             d.suggest(word)  
  7.             word=raw_input()  
  8.         checkedWords = (checkedWords,'05')  
  9.    return checkedWords  

七 去停用词和小写去短词

  1. def CleanWords(self,wordsInStr):#去掉标点符号,长度小于3的词以及non-alpha词,小写化  
  2.     cleanWords=[]  
  3.     stopwords = {}.fromkeys([ line.rstrip()for line in open(conf.PreConfig.ENSTOPWORDS)])  
  4.     for words in wordsInStr:  
  5.         cleanWords+= [[w.lower() for w in words if w.lower() not in stopwords and 3<=len(w)]]  
  6.    return cleanWords  

八 使用Wordnet进行词干化

  1.     def StemWords(self,cleanWordsList):  
  2.         stemWords=[]  
  3. #         porter = nltk.PorterStemmer()#有博士说这个词干化工具效果不好,不是很专业  
  4. #         result=[porter.stem(t) for t incleanTokens]  
  5.         for words in cleanWordsList:  
  6.             stemWords+=[[wn.morphy(w) for w in words]]  
  7.        return stemWords  

九 完整代码

  1. #coding=utf-8  
  2. ''''' 
  3. Created on 2014-3-20 
  4. 英文的词干化和去停用词 
  5. @author: liTC 
  6. '''  
  7. import nltk  
  8. # import enchant  
  9. import string   
  10. import re  
  11. import os  
  12. from config import Config as conf  
  13. from nltk.corpus import wordnet as wn  
  14. import sys  
  15. reload(sys)  
  16. sys.setdefaultencoding('utf-8')  
  17.    
  18. class EnPreprocess:  
  19.     '''''整体流程: 
  20.     读取文件:FileRead()filepath to raw 
  21.     分割成句子:SenToken()raw to sents 
  22.     (词性标注):POSTagger()sent to words[] 
  23.     句子分割成词:TokenToWords()将句子分割成词 sent to word[] 
  24.     (拼写检查):WordCheck() 错误的去掉或是等人工改正 
  25.     去掉标点,去掉非字母内容:CleanLines()句子,line to cleanLine 
  26.     去掉长度小于3的词,小写转换,去停用词:CleanWords(),words[] to cleanWords[] 
  27.     词干化:StemWords()把词词干化返回,words to stemWords 
  28.     二次清理:再执行一次CleanWords(),使句子更加纯净 
  29.     '''  
  30.     def__init__(self):  
  31.         print'English token and stopwords remove...'  
  32.     defFileRead(self,filePath):#读取内容  
  33.         f =open(filePath)  
  34.        raw=f.read()  
  35.         return raw  
  36.     defWriteResult(self,result,resultPath):  
  37.        self.mkdir(str(resultPath).replace(str(resultPath).split('/')[-1],''))  
  38.        f=open(resultPath,"w"#将结果保存到另一个文档中  
  39.        f.write(str(result))  
  40.         f.close()  
  41.     defSenToken(self,raw):#分割成句子  
  42.        sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')  
  43.         sents =sent_tokenizer.tokenize(raw)  
  44.         return  sents  
  45.     def POSTagger(self,sent):  
  46.        taggedLine=[nltk.pos_tag(sent) for sent in sents]  
  47.         returntaggedLine  
  48.     defWordTokener(self,sent):#将单句字符串分割成词  
  49.         result=''  
  50.         wordsInStr= nltk.word_tokenize(sent)  
  51.         returnwordsInStr  
  52.     defWordCheck(self,words):#拼写检查  
  53.         d =enchant.Dict("en_US")  
  54.        checkedWords=()  
  55.         for word inwords:  
  56.             if notd.check(word):  
  57.                d.suggest(word)  
  58.                word=raw_input()  
  59.            checkedWords = (checkedWords,'05')  
  60.         returncheckedWords  
  61.     defCleanLines(self,line):  
  62.         identify =string.maketrans('''')  
  63.         delEStr =string.punctuation + string.digits #ASCII 标点符号,数字    
  64. #         cleanLine= line.translate(identify, delEStr) #去掉ASCII 标点符号和空格  
  65.         cleanLine =line.translate(identify,delEStr) #去掉ASCII 标点符号  
  66.         returncleanLine  
  67.     defCleanWords(self,wordsInStr):#去掉标点符号,长度小于3的词以及non-alpha词,小写化  
  68.        cleanWords=[]  
  69.         stopwords ={}.fromkeys([ line.rstrip() for line in open(conf.PreConfig.ENSTOPWORDS)])  
  70.         for wordsin wordsInStr:  
  71.            cleanWords+= [[w.lower() for w in words if w.lower() not in stopwordsand 3<=len(w)]]  
  72.         returncleanWords  
  73.     defStemWords(self,cleanWordsList):  
  74.        stemWords=[]  
  75. #         porter =nltk.PorterStemmer()#有博士说这个词干化工具效果不好,不是很专业  
  76. #        result=[porter.stem(t) for t in cleanTokens]  
  77.         for wordsin cleanWordsList:  
  78.            stemWords+=[[wn.morphy(w) for w in words]]  
  79.         returnstemWords  
  80.     defWordsToStr(self,stemWords):  
  81.         strLine=[]  
  82.         for wordsin stemWords:  
  83.            strLine+=[w for w in words]  
  84.         returnstrLine  
  85.     defmkdir(self,path):  
  86.         # 去除首位空格  
  87.        path=path.strip()  
  88.         # 去除尾部 \ 符号  
  89.        path=path.rstrip("\\")  
  90.         # 判断路径是否存在  
  91.         # 存在    True  
  92.         # 不存在  False  
  93.        isExists=os.path.exists(path)  
  94.         # 判断结果  
  95.         if notisExists:  
  96.             # 如果不存在则创建目录  
  97.             printpath+' 创建成功'  
  98.             # 创建目录操作函数  
  99.            os.makedirs(path)  
  100.             returnTrue  
  101.         else:  
  102.             # 如果目录存在则不创建,并提示目录已存在  
  103.             printpath+' 目录已存在'  
  104.             returnFalse  
  105.     defEnPreMain(self,dir):  
  106.         forroot,dirs,files in os.walk(dir):  
  107.           foreachfiles in files:  
  108.            croupPath=os.path.join(root,eachfiles)  
  109.             printcroupPath  
  110.            resultPath=conf.PreConfig.NLTKRESULTPATH+croupPath.split('/')[-2]+'/'+croupPath.split('/')[-1]             
  111.            raw=self.FileRead(croupPath).strip()  
  112.            sents=self.SenToken(raw)  
  113. #             taggedLine=self.POSTagger(sents)#暂不启用词性标注  
  114.            cleanLines=[self.CleanLines(line) for line in sents]  
  115.            words=[self.WordTokener(cl) for cl in cleanLines]  
  116. #            checkedWords=self.WordCheck(words)#暂不启用拼写检查  
  117.            cleanWords=self.CleanWords(words)  
  118.            stemWords=self.StemWords(cleanWords)  
  119. #            cleanWords=self.CleanWords(stemWords)#第二次清理出现问题,暂不启用  
  120.            strLine=self.WordsToStr(stemWords)  
  121.            self.WriteResult(strLine,resultPath)#一个文件暂时存成一行  
  122.     defStandardTokener(self,raw):  
  123.         result=''  
  124.         #还没弄好  
  125.         returnresult  
  126.      
  127.      
  128. enPre=EnPreprocess()  
  129. enPre.EnPreMain(conf.PreConfig.ENCORUPPATH)  

PS:一直还没用好Stanford的那个工具包,谁用过教我一下吧
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值