正向最大匹配算法 python_Python基于词典的正向最大匹配

本文介绍了一个基于词典的正向最大匹配(FMM)算法的Python实现,用于分词处理。首先,通过正则表达式整理输入文本,然后加载词典,最后运用FMM算法进行分词,将连续的最大长度单词切分出来。
摘要由CSDN通过智能技术生成

分词的好坏取决于词典

'''

基于词典的正向最大匹配算法

@author Sirius

'''

import re

#载入汪峰的《存在》歌词

def data():

with open('存在.txt','r',encoding='utf-8') as f:

data = f.read()

#正则表达式把多个空格换成一个空格,txt中出现的标点和特殊字符作为句子的分隔

mode_strip = re.compile(r'\n\n+')

data_strip = re.sub(mode_strip, '\n', data)

mode = re.compile(r'[,。《》\n]')

sentences = re.split(mode, data)

return sentences

#载入词典

def load_dic():

with open('dic.txt','r',encoding='utf-8') as f:

dic = f.read()

dic = dic.split('\n')

return dic

#正向最大匹配算法

def FMM(sents, MaxLen):

s1 = sents;

s2 = '';

while s1 != '':

lens = MaxLen

if len(s1) < lens:

lens = len(s1)

word = s1[:lens]

dic = load_dic()

while word not in dic:

word = word[:len(word)-1]

if len(word) == 1:

break;

s2 = s2 + word + '\\'

s1 = s1[len(word):]

return s2

if __name__ == '__main__':

print(FMM('研究生命的起源',4))

'''

result = ''

for sent in data():

s2=FMM(sent, 4)

if s2 != '':

result = result + s2 + ','

print(result[:len(result)-1])

'''

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值