note 12 集合Set

集合Set

+无序不重复元素(键)集
+和字典类似,但是无“值”

创建

x = set()
x = {key1,key2,...}

添加和删除

x.add('body')
x.remove('body')

集合的运算符

运算符 含义

  •        差集
    & 交集
    | 并集
    != 不等于
    == 等于
    in 成员
    for key in set 枚举

+中文分词
如:我爱北京天安门。->我/爱/北京/天安门/。
算法:正向最大匹配
从左到右扫描取尽可能长的词
如:研究生命的起源->研究生/命/的/起源
“研究生”是词,且比“研究”更长

自然语言处理

处理此问题需要一个词典

正向最大匹配分词

def load_dict(filename):
    word_dict = set()
    max_len = 1
    f =  open(filename)
    for line in f:
        word = unicode(line .strip(),'utf-8')
        word_dict.add(word)
        if len(word) > max_len:
            max_len = len(word)
            
    return max_len,word_dict

def fmm_word_seg(sent,max_len,word_dict):
    begin = 0
    words = []
    sent = unicode(sent,'utf-8')
    
    while begin < len(sent):
        for end in range(begin + max_len,begin,-1):
            if sent[begin:end] in word_dict:
                words.append(sent[begin:end])
                break
        begin = end
        
    return words

max_len,word_dict = load_dict('lexicon.dic')
sent = raw_input('Input a sententce:')
words = fmm_word_seg(sent,max_len,word_dict)
for word in words:
    print word

数据结构对比

猜你喜欢

转载自www.cnblogs.com/OceanF/p/10781356.html