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

高洛峰
发布: 2016-10-18 14:41:11
原创
2749人浏览过

说到分词大家肯定一般认为是很高深的技术,但是今天作者用短短几十行代码就搞定了,感叹python很强大啊!作者也很强大。不过这个只是正向最大匹配,没有机器学习能力

注意:使用前先要下载搜狗词库

# -*- coding:utf-8 -*-
   
#写了一个简单的支持中文的正向最大匹配的机械分词,其它不用解释了,就几十行代码
#附:搜狗词库下载地址:http://vdisk.weibo.com/s/7RlE5
   
import string
__dict = {}
   
def load_dict(dict_file='words.dic'):
    #加载词库,把词库加载成一个key为首字符,value为相关词的列表的字典
   
    words = [unicode(line, 'utf-8').split() for line in open(dict_file)]
   
    for word_len, word in words:
        first_char = word[0]
        __dict.setdefault(first_char, [])
        __dict[first_char].append(word)
      
    #按词的长度倒序排列
    for first_char, words in __dict.items():
        __dict[first_char] = sorted(words, key=lambda x:len(x), reverse=True)
   
def __match_ascii(i, input):
    #返回连续的英文字母,数字,符号
    result = ''
    for i in range(i, len(input)):
        if not input[i] in string.ascii_letters: break
        result += input[i]
    return result
   
   
def __match_word(first_char, i , input):
    #根据当前位置进行分词,ascii的直接读取连续字符,中文的读取词库
   
    if not __dict.has_key(first_char):
        if first_char in string.ascii_letters:
            return __match_ascii(i, input)
        return first_char
   
    words = __dict[first_char]
    for word in words:
        if input[i:i+len(word)] == word:
            return word
   
    return first_char
   
def tokenize(input):
    #对input进行分词,input必须是uncode编码
   
    if not input: return []
   
    tokens = []
    i = 0
    while i < len(input):
        first_char = input[i]
        matched_word = __match_word(first_char, i, input)
        tokens.append(matched_word)
        i += len(matched_word)
   
    return tokens
   
   
if __name__ == '__main__':
    def get_test_text():
        import urllib2
        url = "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, words in __dict.items():
            print '%s:%s' % (first_char, ' '.join(words))
   
    def tokenize_test(text):
        load_dict()
        tokens = tokenize(text)
        for token in tokens:
            print token
   
    tokenize_test(unicode(u'美丽的花园里有各种各样的小动物'))
    tokenize_test(get_test_text())
登录后复制
python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号