第三次重新写这个算法,每次写都有新的体会。
这次最大的感受是把访问文件夹的包都熟悉了一下,os和shutil。后者用来删除整个文件,这种破坏力还是慎用吧。
def mk_new_dir(filename): # 新建一个文件夹,如果存在,则删除并重建。 if os.path.exists(filename) is True: shutil.rmtree(filename) os.mkdir(filename)下面是最大逆向匹配核心部分:
def rmm(dicwords, lines, n, filepath): """最大逆向匹配: 最大逆向匹配算法,需要分词词典[];待分割文本[];设定分割长度int """ global BUS # for line in lines: if line.strip().replace(' ', '').replace('\n', '') != '': BUS = [] # 释放 line = line.strip().replace('\n', '').replace(' ', '') # 清洗 # print(line) line_len = len(line) # 句长 if line_len < n: n = line_len # 如果句长短语规定切分长度,则设置规定切分长度为句长 # print(str(n)) start = n s = line[-start:] # 获取待分割语句 t = rmm_cut(s, dicwords) # 获取已切分词长,用来加工下一次取词 end = t while end < line_len: # 核心部分,实现对句子的循环取词 start = start + t s = line[-start:-end] # print(s) t = rmm_cut(s, dicwords) # 已切分词长 end = end + t filewrite(BUS, filepath) # 写入结果文件 def rmm_cut(s, dicwords): """逆向匹配,分函数""" flag = True global BUS # print(s) while flag is True: # 循环切分 if s in dicwords: s = '/' + s BUS.append(s) flag = False return len(s) - 1 # 对返回的数进行-1处理,保证下一次的取词正确 elif len(s) == 1: s = '/' + s BUS.append(s) flag = False return 1 else: s = s[1:]rmm(词典列表,读入的文本,每次取句子最大长度,存储文本路径)
rmm_cut(取得的长句,词典列表)
不论正向还是逆向匹配,都需要运用到Python的切片功能,把过程搞明白,就能很好的实现匹配功能。
