当前位置:Gxlcms > Python > python实现中文分词FMM算法实例

python实现中文分词FMM算法实例

时间:2021-07-01 10:21:17 帮助过:61人阅读

本文实例讲述了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程序设计有所帮助。

人气教程排行