美文网首页
用python做语言处理入门

用python做语言处理入门

作者: 00crazy00 | 来源:发表于2016-05-10 22:36 被阅读0次

今天突发奇想,想来做做关于英文文章的词汇统计,及文章相似度计算,来检验下python的编程能力。我首先想到的是将英文文章中的词汇提取出来,用向量来描绘单词出现频数,然后两篇文章之间相关度可以用向量之间范数表示。

            f=input("input the file to analyze\n")
            txt=open(f,"r").read()    txt=txt.lower()#转换为小写
            for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}]~':
                     txt=txt.replace(ch," ")
            words=txt.split( )
            counts={}
            for w in words:
                counts[w]=counts.get(w,0)+1
            items=sorted(counts.items(),key=lambda x:x[1],reverse=True)#按照字典的键值排序
            for i in range(20):
               word,count=items[i]
               print('{0:<15}{1:>5}'.format(word,count))
split1() ``` 
随手找了一篇英语新闻,算了算词汇频数。
![R%3[}RC52GB1}O2SPXG`8YM.png](https://img.haomeiwen.com/i2022449/92376e9ccf35927a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这种方法有很大局限性,如果两个单词意思一样,词性不一样,就会识别为不同单词,这样不精准。然后就百度了下,发现机器学习sklearn和nltk都有很强大的语言处理能力,就使用来替代我的程序。
``` import nltk.stemfrom
      sklearn.feature_extraction.text import CountVectorizer
      def opentxt():
             f = input("input the file to analyze\n")
             txt1 = open(f, "r").read()
             return txt1def fenci(txt1):
             vectorer=CountVectorizer(min_df=1)#建立一个分词对象
             txt2=[txt1]
             X=vectorer.fit_transform(txt2)
             Y=vectorer.get_feature_names()#得到词汇列表
             m,n=X.shape    
             for i,j in zip(Y,X):
                 print(i,j)
a=opentxt()
fenci(a) ```
明天接着写

相关文章

网友评论

      本文标题:用python做语言处理入门

      本文链接:https://www.haomeiwen.com/subject/kyvyrttx.html