看了一段时间了的自然语言,不过还是很初级。

今天下载了一个分词的字典,自己用python写了一个分词的函数。

放上来,给大家踩,不吝赐教!

用的是最大匹配算法。

# -*- coding: cp936 -*-

import string

def loaddict():
filename=raw_input('Enter file name:')
f = open(filename,'r')

DICT={}
for eachLine in f:
dictStr = eachLine.decode('cp936')
strList=dictStr.split("\t",2)
DICT[strList[0]]=strList[1].split("\n",1)[0]
global DIC_MAXL
if(DIC_MAXL<len(strList[0])):
DIC_MAXL = len(strList[0])
f.close()
print("max length:")
print(DIC_MAXL)
return DICT;

def segmentation(dic):
sentence = unicode(raw_input('请输入中文句子:'),'cp936')
print sentence
length=len(sentence)
print('length:')
print length
global DIC_MAXL
if(length<DIC_MAXL):
wlen=length
else:
wlen=DIC_MAXL
testS=sentence
wordList=[]
while(len(testS)>0):
word=testS[0:wlen]
meet=False;
while((not meet )and (len(word)>0) ):
if(dic.has_key(word)):
wordList.append(word)
testS=testS[len(word):len(testS)]
meet=True;
else:
if(len(word)==1):
wordList.append(word)
testS=testS[len(word):len(testS)]
meet=True;
else:
word=word[0:len(word)-1]
return wordList

DIC_MAXL=0
dictionary=loaddict()
print DIC_MAXL
while(True):
wordl=segmentation(dictionary)
for eachChar in wordl:
print eachChar

真的很初级,大家轻踩!

也别不好意思踩,踩了我就能进步了!

多谢

作者 ricky

《初学者报到: 实现了一个最大匹配的分词算法》有12条评论
  1. 多谢分享;另外发现你发文章时选择了“日志”,所以首页显示不了题目,我改了一下!

    [回复]

  2. 谢谢。
    不好意思,是不是以后都用 “标准” 来发文章?。
    第一次发不知道!

    [回复]

    52nlp 回复:

    嗯,应该是选择“标准”来发文章。

    [回复]

    小齐 回复:

    你们好,能加我qq吗?我有点问题想请教你们?谢谢了哥哥们?1154195581

    [回复]

    52nlp 回复:

    抱歉,那个qq群不是我建的,我也没有加在里面。

    小齐 回复:

    你好哥,能加你qq请教一下吗?非常感谢你啊

    52nlp 回复:

    有问题可以考虑邮箱联系我:52nlpcn#gmail.com,不保证能解决你的问题,暂不加qq,抱歉!

  3. 谢谢版主的分享,我也想学一下中文分词的东西。版主给出的代码没有缩进,不便于阅读,能否改进一下?谢谢了

    [回复]

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注