大佬们,我用了逆向最大匹配分词法,为啥会出现这种情况,救救我这个菜鸡
震惊了! 你不提供更多信息我们怎么能帮你呢?
import codecs
import xlrd2
def readfile(raw_file_path):
with codecs.open(raw_file_path,'r',encoding='utf8')as f:
raw_file=f.readlines()
return raw_file
#读取待分词的文本,使用.read lines()函数,返回句子的list但是我的list暂时还没有看见
def read_dic(dic_path):
words_excel=xlrd2.open_workbook(dic_path)
sheet=words_excel.sheets()[0]
data_list=list(sheet.col_values(1))[1:]
return data_list
#读取分词的excel文件,要从文件的第二行开始读,暂时还是什么都没有
def cut_words(raw_sentences,word_dict):
max_length=(max(len(word) for word in word_dict))
word_cut=[]
#规定分词的词组最大长度,这里取了词表中最长的词组的长度
for sentence in raw_sentences:
sentence=sentence.strip()
#使用strip函数去掉字符串两边的空格
words_length=len(sentence)
cut_word_list=[]
while words_length>0:
max_cut_length=(min(words_length,max_length))
#选取词长和最大长度中较小的那一个
for i in range(max_cut_length,0,-1): #没明白这句是什么意思
new_word=[-max_cut_length]
#从后向前开始截词
if new_word in word_dict:
cut_word_list.append(new_word)
#如果截词在词典中存在,那么就把它分出来
words_length=words_length-i
break
elif i==1:
cut_word_list.append(new_word)
words_length=words_length-1
cut_word_list.reverse()
#逆向最大匹配后要把顺序正过来
words='/'.join(str(cut_word_list))
word_cut.append(words.lstrip('/'))
#把句子左端分词符号去掉防止出现分子里有空白的情况
return word_cut
def outfile(out_path,sentences):
#建立输出文本
with codecs.open(out_path,'a','utf8')as f:
#a的意思是在原始文本上追加文本
for sentence in sentences:
f.write(sentence)
def main():
raw_file_path=r"C:\Users\Apple\Desktop\7.txt"
raw_file=readfile(raw_file_path)
#需要被分词的文本
wordfile_path=r"C:\Users\Apple\Desktop\词表.xlsx"
words_dic=read_dic(wordfile_path)
#读取词典的路径
content_cut=cut_words(raw_file,words_dic)
#逆向最大分词
outfile_path=r"C:\Users\Apple\Desktop\分词结果.txt"
outfile(outfile_path,content_cut)
#输出文件
if __name__ == '__main__':
main()
大佬,这是我看别人的代码写出来的,结果就出现了上述情况,肿么办?