日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用几十行代码实现python中英文分词

發布時間:2024/5/7 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用几十行代码实现python中英文分词 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

說到分詞大家肯定一般認為是很高深的技術,但是今天作者用短短幾十行代碼就搞定了,感嘆python很強大啊!作者也很強大。不過這個只是正向最大匹配,沒有機器學習能力

注意:使用前先要下載搜狗詞庫

# -*- coding:utf-8 -*-#寫了一個簡單的支持中文的正向最大匹配的機械分詞,其它不用解釋了,就幾十行代碼 #附:搜狗詞庫下載地址:http://vdisk.weibo.com/s/7RlE5import string __dict= {}def load_dict(dict_file='words.dic'):#加載詞庫,把詞庫加載成一個key為首字符,value為相關詞的列表的字典words= [unicode(line,'utf-8').split()for linein open(dict_file)]for word_len, wordin words:first_char= word[0]__dict.setdefault(first_char, [])__dict[first_char].append(word)#按詞的長度倒序排列for first_char, wordsin __dict.items():__dict[first_char]= sorted(words, key=lambda x:len(x), reverse=True)def __match_ascii(i,input):#返回連續的英文字母,數字,符號result= ''for iin range(i,len(input)):if not input[i]in string.ascii_letters:breakresult+= input[i]return resultdef __match_word(first_char, i ,input):#根據當前位置進行分詞,ascii的直接讀取連續字符,中文的讀取詞庫if not __dict.has_key(first_char):if first_charin string.ascii_letters:return __match_ascii(i,input)return first_charwords= __dict[first_char]for wordin words:if input[i:i+len(word)]== word:return wordreturn first_chardef tokenize(input):#對input進行分詞,input必須是uncode編碼if not input:return []tokens= []i= 0while i <len(input):first_char= input[i]matched_word= __match_word(first_char, i,input)tokens.append(matched_word)i+= len(matched_word)return tokensif __name__== '__main__':def get_test_text():import urllib2url= "http://news.baidu.com/n?cmd=4&class=rolling&pn=1&from=tab&sub=0"text= urllib2.urlopen(url).read()return unicode(text,'gbk')def load_dict_test():load_dict()for first_char, wordsin __dict.items():print '%s:%s' % (first_char,' '.join(words))def tokenize_test(text):load_dict()tokens= tokenize(text)for tokenin tokens:print tokentokenize_test(unicode(u'美麗的花園里有各種各樣的小動物'))tokenize_test(get_test_text())

總結

以上是生活随笔為你收集整理的用几十行代码实现python中英文分词的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。