语言模型的作用是在大量的训练样例中,给出一个句子求出概率,其中应用的技术有平滑、 统计语言模型。

假设S表示某一个有意义的句子,由一连串特定顺序排列的词w1、w2、w3、...、wn组成,利用条件概率公式,能够得到:

P(S)=P(W1,W2,W3,...,Wn)

=P(W1)P(W2|W1)P(W3|W1,W2)…P(Wn|W1,W2,…,Wn-1)

P(W1)    —— 第一个词W1出现的概率

P(W2|W1)—— 已知第一个词W1的前提下,第二个词W2出现的概率

根据马尔科夫模型,

任意一个词出现的概率只与它前面出现的有限的1个或着i个词有关。

如句子,“我爱打篮球”的概率:

二元模型:P(我) * P(爱|我) * P(打|爱) * P(篮球|打)

三元模型:P(我,爱) * P(打|我,爱) * P(篮球|爱,打)

P(我,爱) = P(我) * (爱|我)

•     Goal:compute the probability of a sentence or sequence of words:

P(W) = P(w1,w2,w3,w4,w5…wn)

•     Related task: probability of an upcoming word:

P(w5|w1,w2,w3,w4)

•     Amodel that computes either of these:

P(W)     or    P(wn|w1,w2…wn-1)          is called alanguage model.

•     Better:the grammar       But languagemodel or LM is standard

根据语言模型和统计结果确定候选集,完成推荐下一个词的任务。

实践步骤:

1、获取语料库资料

2、分词统计

3、以一定格式输出到文本中

4、读入文本

5、分词

6、查找文本中的资料

7、排序

8、输出前5个结果

主要的问题包括:

1、需要大量的多领域语料库。

2、运行效率和存储空间,是时间和空间的折衷处理。

3、可以加入词性考虑。

代码:

获取一个文件夹下全部文件:

#读取目录内所有文件,返回文件路径列表
def readAllFiles(baseDir, fileList):filelist=os.listdir(baseDir)for dir in filelist:if os.path.isdir(baseDir+'/'+dir):readAllFiles(baseDir+'/'+dir, fileList)else:fileList.append(baseDir+'/'+dir)

读取文件:

def readFile(url):dataset = open(url, 'r+', encoding='utf-8').read()

核心统计词频,其中包含去除文件中的词性标注:

#统计词频,三个单词
def frequency(sentence, dicts, N=2, replace=True, split_string='  '):#排除词性标注if replace==True:sentence = sentence.replace('\n', '').replace('/', '')for alp in alp_table:sentence=sentence.replace(alp, '')lists=sentence.split('  ')preword_list=[]total_word=0#list是当前的sentence词语集合的列表for word in lists:#代表句子的结尾if word in symbol_table:temp = dictsfor preword in preword_list:temp = temp[pre· word]if preword_list!=[]:temp[' '] += 1preword_list = []continue#去除词语中的无意义标注,如胖子&#中的&,#for ch in forbidden_table:if ch in word:word.replace(ch, '')if word not in word_dict:word_dict[word]=1else:word_dict[word]+=1total_word+=1if len(preword_list)==N:temp=dictsfor preword in preword_list:temp=temp[preword]temp[' ']+=1preword_list.pop(0)temp=dictsfor preword in preword_list:if preword not in temp:temp[preword]={' ':0}temp=temp[preword]if word not in temp:temp[word]={' ':0}preword_list.append(word)return total_word

把字典转换为格式化字符串,把字典转换为方便排序的列表:

def dict2str(dicts):result=""for dic in dicts:if dic==' ':continue#result+=dic+' '+str(dicts[dic])+'\n'else:temp=dicts[dic]for dic2 in temp:if dic2 == ' ':result+=dic+' '+str(temp[dic2])+'\n'else:temp2=temp[dic2]for dic3 in temp2:if dic3==' ':result+=dic+' '+dic2+' '+str(temp2[dic3])+'\n'else:result+=dic+' '+dic2+' '+dic3+' '+str(temp2[dic3][' '])+'\n'return resultdef dict2list(dic:dict):''' 将字典转化为列表 '''keys = dic.keys()vals = dic.values()lst = [(key, val) for key, val in zip(keys, vals)]return lst

运行函数:

import os
alp_table = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_']
symbol_table = [',', '。', '!', '?', ';', '、', '/', '(', ')', '《', '》', '——', '\'', '\"']+alp_table
num_table = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']forbidden_table = ['&','#',',', '。', '!', '?', ';', '、', '/', '(', ')', '《', '》', '——', '\'', '“', '”', '【', '】']+symbol_table+alp_table+num_table
dataset=""
word_dict={}
if __name__=='__main__':dicts = {}files_list = []# 读取全部文件readAllFiles('./corpus2/corpus', files_list)# 对每个文件进行识别单词操作for file in files_list:fp = open(file, 'r+')frequency(fp.read(), dicts, N=3)fp.close()fp = open('dict.txt', 'a')word_dict=sorted(word_dict.items(), key=lambda x:x[1],reverse=True)for k in word_dict:fp.write(k[0]+' '+str(k[1])+'\n')#print(len(lst))fp.close()

预处理结束后,进行第二步查询结果:

核心函数,预测,功能是读入文件,进行统计排序:

fp=open('result3.txt', 'r')
dataset=fp.read().split('\n')
fp.close()
#输入词组列表后预测
def Predict2(sentence, urlPath='result3.txt'):word_list=" ".join(jieba.cut(sentence, HMM=False)).split(' ')if (len(word_list) <= 0):return Falseresult_dict={}start=Falseif len(word_list)==1:for data in dataset:words = data.split(' ')if len(words)<3:continueif word_list[0]==words[0]:start=Trueif words[1] not in result_dict:if len(words) == 3:result_dict[words[1]] = int(words[2])else:result_dict[words[1]] = int(words[3])else:if len(words) == 3:result_dict[words[1]] += int(words[2])else:result_dict[words[1]] += int(words[3])'''else:if start==True:break'''else:for data in dataset:words = data.split(' ')if len(words)!=4:continueif word_list[-2]==words[0] and word_list[-1]==words[1]:#start=Trueresult_dict[words[2]] =int(words[3])'''else:if start==True:break'''result_list = dict2list(result_dict)result_list.sort(key=lambda item:item[1], reverse=True)return result_list

最后,输入句子,利用jieba分词,可以得到最终结果:

alp_table = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v','w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G','H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_']
symbol_table = [',', '。', '!', '?', ';', '、', '/', '(', ')', '《', '》', '——', '\'', '\"', ';']+alp_table
num_table = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']forbidden_table = ['&','#',',', '。', '!', '?', ';', '、', '/', '(', ')', '《', '》', '——', '\'', '“', '”', '【', '】']+symbol_table+alp_table+num_table#begin = datetime.datetime.now()
#list=Predict('坐')
#end = datetime.datetime.now()
#print(end-begin)
if __name__=='__main__':print('按q退出程序')while True:s = input('输入句子:')if (s == 'q'):breakword_list = " ".join(jieba.cut(s, HMM=False)).split(' ')start=datetime.datetime.now()lkk = Predict2(s)lst=[]for word in lkk:ok=Truefor ch in forbidden_table:if ch in word[0]:ok=Falsebreakif(ok==True):lst.append(word)if(len(lst)==5):breaklength=len(lst)if length < 5:length = 5fp = open('dict.txt', 'r')lines = fp.readlines()for line in lines:templst = line.split(' ')word=templst[0]templst[1] = templst[1].split('\n')[0]if (word in lst) or (word in word_list):continueok = Truefor ch in forbidden_table:if ch in word:ok = Falsebreakif (ok == True):lst.append(templst)if (len(lst) == 5):breakfp.close()result = "推荐: "for i in range(length):result += lst[i][0] + str(lst[i][1]) + '  'print(result + '\n')end = datetime.datetime.now()print(end - start)

实现效果:

文件保存形式:

到此完成推荐词语的任务,记得安装jieba分词,可以免去输入分词。

有大规模中文语料推荐的朋友可以搜索“搜狗实验室”中的全网新闻数据,训练模型效果更好!

//有需要语料库的朋友可以留言告知。

python实现三元语言模型与输入法推荐相关推荐

  1. Python入门教程:很多人推荐学 Python 入 IT ,如果学完 Python 找不到工作怎么办...

    Python入门教程:很多人推荐学 Python 入 IT ,但是如果学完 Python 找不到工作怎么办,这也是很多人担心的问题. 很多人推荐通过学习 Python 入行 IT 一是因为 Pytho ...

  2. 关于python的一些好的书籍推荐-python官方推荐30本面向初学者的书籍!你看过几本?...

    现在大多数初学者学习python都是看教学视频,但是小编想说的是,如果你能把一本书籍认认真真的读完,那么比你看教学视频的效果要好的多!今天小编就来带大家看看python官方推荐的30本面向初学者的书籍 ...

  3. 关于python的一些好的书籍推荐-荐书||关于Python的一些书籍推荐

    为什么要学Python? 因为... 管它用的到,或是用不到,看一看拓宽思路也是极好的. 入门篇 <A Byte of Python> 豆瓣评分:8.7 推荐人群:初学者,短时间内想了解P ...

  4. python入门基础代码图-python入门代码指南教程书籍推荐2020总结全集汇总

    python入门代码指南教程书籍推荐2020总结全集汇总 记住,如果您想学习Python,市场上有很多可用的资源.这些可以包括书籍,甚至在线课程..在这篇文章中,我们为Python编写了最好的书籍,无 ...

  5. python编辑器_初学Python这几款编辑器,推荐你安装

    编程这个东西是真的奇妙.对于懂得的人来说,会觉得这个工具是多么的好用.有趣,而对于小白来说,就如同大山一样.其实这个都可以理解,大家都是这样过来的.那么接下来千锋武汉Python培训小编就说一下Pyt ...

  6. 搜狗输入法电脑版_四款“真·无广告”的良心靠谱输入法推荐 2020

    前言 输入法对我们来说无疑是最基本的必备软件了,因此选一个不流氓且无广告的输入法相当重要. 谁都不想电脑右下角时不时地弹一个广告,尤其是618和双十一时!拦截软件都拦不住,非常烦人. 下面就分享四款「 ...

  7. python之三元表达式嵌套三元表达式解析

    python的三元表达式相信学过python的朋友都会.但是大部分学python的朋友不知道的是三元表达式还可以嵌套三元表达式. 请看代码案例: cmp = lambda a, b: 0 if a = ...

  8. 从入门到入土:Python实现爬取刷新微博推荐和最新好友微博|cookie调用|模拟登录

    写在前面: 此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) Python实现爬取刷新微博推荐和最新好友微博|cookie ...

  9. python入门代码大全-python入门代码指南教程书籍推荐2020总结全集汇总

    python入门代码指南教程书籍推荐2020总结全集汇总 记住,如果您想学习Python,市场上有很多可用的资源.这些可以包括书籍,甚至在线课程..在这篇文章中,我们为Python编写了最好的书籍,无 ...

最新文章

  1. MavenAnt使用
  2. 交换机的4种网络结构方式你知道是什么吗?
  3. BZOJ 3309 DZY Loves Math
  4. Asp.net之MsChart控件动态绑定温度曲线图
  5. 高斯过程回归python_基于python的高斯过程回归训练集数据扩充
  6. 15个热门的编程趋势及15个逐步走向衰落的编程方向
  7. C++版二叉树非递归遍历
  8. 数据库时区那些事儿 - MySQL的时区处理
  9. docker php 乱码,如何解决docker安装zabbix5.0界面乱码
  10. linux怎么删web应用程序错误,Ubuntu 20.04将删除Amazon Web应用程序,但用户可另行安装...
  11. quartz java spring_从零开始学 Java - Spring 使用 Quartz 任务调度定时器
  12. [SQL]实战之查找员工编号emp_no为10001其自入职以来的薪水salary涨幅值growth
  13. 李秋豪计算机系统,CS:APP3e 深入理解计算机系统_3e Y86-64模拟器指南
  14. poj 3626 Mud Puddles
  15. 2022年常见遥感类期刊JCR分区与影响因子汇总
  16. 天才少年George Hotz在自家车库亲手打造了一台无人自驾驶汽车!
  17. 车好多让10万亿元的汽车消费市场跳起来
  18. mats显存测试软件linux环境,显存检测软件Mats
  19. Linux发展史之简要概述
  20. 作业辅导视频 SS2023-HW10:Laplace变换性质练习题

热门文章

  1. opencv 图片边缘渐变_OpenCV——颜色均匀渐变
  2. Tuxedo安装部署升级补丁
  3. 2020年第十一届蓝桥杯javaB组国赛
  4. 多线程之间如何实现同步?
  5. 山西检察机关出重拳助力污染防治 涉大气水危险废物等领域
  6. 关于电脑出厂时间查询工具的构思
  7. 怎么更改oracle端口,Oracle更改默认端口
  8. JAVA面试208道实用题,答案持续更新整理。
  9. redis修改的源代码zincrby,hincrby命令
  10. Android 选择器