国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現中文分詞FMM算法實例

2020-01-04 18:06:01
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了python實現中文分詞FMM算法,實例分析了Python基于FMM算法進行中文分詞的實現方法,涉及Python針對文件、字符串及正則匹配操作的相關技巧,需要的朋友可以參考下

本文實例講述了python實現中文分詞FMM算法。分享給大家供大家參考。具體分析如下:

FMM算法的最簡單思想是使用貪心算法向前找n個,如果這n個組成的詞在詞典中出現,就ok,如果沒有出現,那么找n-1個...然后繼續下去。假如n個詞在詞典中出現,那么從n+1位置繼續找下去,直到句子結束。

 

 
  1. import re  
  2. def PreProcess(sentence,edcode="utf-8"):  
  3. sentence = sentence.decode(edcode)  
  4. sentence=re.sub(u"[。,,!……!《》<>/"'::?/?、/|“”‘';]"," ",sentence)  
  5. return sentence  
  6. def FMM(sentence,diction,result = [],maxwordLength = 4,edcode="utf-8"): 
  7. i = 0 
  8. sentence = PreProcess(sentence,edcode)  
  9. length = len(sentence)  
  10. while i < length:  
  11. # find the ascii word  
  12. tempi=i  
  13. tok=sentence[i:i+1]  
  14. while re.search("[0-9A-Za-z/-/+#@_/.]{1}",tok)<>None:  
  15. i= i+1 
  16. tok=sentence[i:i+1]  
  17. if i-tempi>0:  
  18. result.append(sentence[tempi:i].lower().encode(edcode))  
  19. # find chinese word  
  20. left = len(sentence[i:])  
  21. if left == 1:  
  22. """go to 4 step over the FMM""" 
  23. """should we add the last one? Yes, if not blank""" 
  24. if sentence[i:] <> " ":  
  25. result.append(sentence[i:].encode(edcode))  
  26. return result  
  27. m = min(left,maxwordLength)  
  28. for j in xrange(m,0,-1):  
  29. leftword = sentence[i:j+i].encode(edcode)  
  30. # print leftword.decode(edcode)  
  31. if LookUp(leftword,diction):  
  32. # find the left word in dictionary  
  33. # it's the right one  
  34. i = j+i  
  35. result.append(leftword)  
  36. break 
  37. elif j == 1:  
  38. """only one word, add into result, if not blank""" 
  39. if leftword.decode(edcode) <> " ":  
  40. result.append(leftword)  
  41. i = i+1 
  42. else:  
  43. continue 
  44. return result  
  45. def LookUp(word,dictionary):  
  46. if dictionary.has_key(word):  
  47. return True 
  48. return False 
  49. def ConvertGBKtoUTF(sentence):  
  50. return sentence.decode('gbk').encode('utf-8'
  51. dictions = {}  
  52. dictions["ab"] = 1 
  53. dictions["cd"] = 2 
  54. dictions["abc"] = 1 
  55. dictions["ss"] = 1 
  56. dictions[ConvertGBKtoUTF("好的")] = 1 
  57. dictions[ConvertGBKtoUTF("真的")] = 1 
  58. sentence = "asdfa好的是這樣嗎vasdiw呀真的daf dasfiw asid是嗎?" 
  59. s = FMM(ConvertGBKtoUTF(sentence),dictions)  
  60. for i in s:  
  61. print i.decode("utf-8"
  62. test = open("test.txt","r")  
  63. for line in test:  
  64. s = FMM(CovertGBKtoUTF(line),dictions)  
  65. for i in s:  
  66. print i.decode("utf-8"

運行結果如下:

asdfa

好的

vasdiw

真的

daf

dasfiw

asid

?

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永修县| 叙永县| 庄河市| 旺苍县| 彭阳县| 咸阳市| 图木舒克市| 东乡| 阿拉尔市| 荆州市| 沭阳县| 盐边县| 和田市| 兴山县| 封丘县| 裕民县| 湾仔区| 林州市| 开封县| 新余市| 墨江| 三亚市| 邯郸市| 云南省| 多伦县| 蒙自县| 依安县| 陕西省| 南昌市| 来宾市| 伊吾县| 陵川县| 疏附县| 江山市| 醴陵市| 盘山县| 攀枝花市| 东台市| 辽中县| 泰来县| 赤水市|