国产探花免费观看_亚洲丰满少妇自慰呻吟_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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福贡县| 海盐县| 平舆县| 武胜县| 达孜县| 乌审旗| 兰州市| 白水县| 甘德县| 望江县| 上林县| 武胜县| 横峰县| 泗水县| 宜城市| 永川市| 宣城市| 五常市| 惠水县| 武义县| 吉安市| 陇西县| 东山县| 马龙县| 年辖:市辖区| 新昌县| 定襄县| 晋中市| 南乐县| 剑阁县| 大冶市| 晋江市| 江西省| 晋江市| 环江| 桂林市| 唐海县| 宜黄县| 盐亭县| 柏乡县| 孟连|