# -*-coding:utf-8-*-from __future__ import division
from nltk.book import *"""搜索文本
"""
# print text1
# print text1.concordance('monstrous')  # 查找有这个单词的句子,并显示出来
# print '------------------------------'
# print text1.similar('monstrous')  # 还有那些词出现在相似的上下文中
# print text2.similar('monstrous')
# print '------------------------------'
# print text2.common_contexts(['monstrous', 'very'])  # 共同的上下文
# print '------------------------------'
# print text4.dispersion_plot(['citizens', 'freedom', 'duties', 'America'])  # 用图像将文本中单词出现的位置标记出来
# print '------------------------------'"""计数词汇
"""
# print len(text3)  # 输出text3中的文本中字符个数
# print sorted(set(text2))  # 输出文本中排序后的结果,并进行去重处理
# print len(set(text2))
# print '-------------------------'# from __future__ import division  # 每个词被使用的次数
# print len(text2)/len(set(text2))
# print text2.count('the')  # 统计一个词在文本中出现的次数
# print 100*text2.count('the')/len(text2)  # 计算一个词在文本中占据的百分比# 使用函数
# def lexical_diversity(text):
#     return len(text)/len(set(text))
# def percentage(count, total):
#     return 100*count/total
#
# print lexical_diversity(text6)
# print lexical_diversity(text9)"""链表(list)连接 +追加 appand()索引 text[10]切片 text[10:100]排序 sorted()去重 set()
"""
"""频率分布:FreqDist()来寻找频率找到一本书使用最频繁的50个词
"""
# fdist = FreqDist(text9)
# print fdist  # 总的词数有69213个
# voc = fdist.keys()
# print voc[:50]
# # print fdist.plot(50, cumulative=True)  # 将文本中出现词数最多的前50个根据频率用图表示出来
# print fdist.hapaxes()  # 只出现了一次的词"""细粒度选择词:选择长度大于15的词
"""
# v = set(text2)
# long_words = [w for w in v if len(w) > 15]
# print sorted(long_words)"""词语搭配和双连词
"""
print text4.collocations()
print text8.collocations()"""计数的其他东西:fdist = FreqDist(samples)   创建包含给定样本的频率分布fdist.inc(sample)           增加样本fdist['monstrous']          计数给定样本出现的次数fdist.freq('monstrous')     给定样本的频率fdist.N()                   样本总数fdist.keys()                以频率递减顺序排序的样本链表for sample in fdist:        以频率递减的顺序遍历样本fdist.max()                 数值最大的样本fdist.tabulate()            绘制频率分布表fdist.plot()                绘制频率分布图fdist.plot(cumulative=True) 绘制累积频率分布图fdist1<fdist2               测试样本在fdist1中出现的频率是否小于fdist2
"""
"""s.startswith(t)  测试 s是否以t开头s.endswith(t)    测试 s是否以t结尾t in s           测试 s是否包含ts.islower()      测试 s中所有字符是否都是小写字母s.isupper()      测试 s中所有字符是否都是大写字母s.isalpha()      测试 s中所有字符是否都是字母s.isalnum()      测试 s中所有字符是否都是字母或数字s.isdigit()      测试 s中所有字符是否都是数字s.istitle()      测试 s是否首字母大写( s中所有的词都首字母大写
""""""思考:既然NLTK这么有用,那么对于中文的处理又该如何处理呢??方法:1、使用中文分词器(jieba)2、对中文字符做编码处理,使用unicode编码方式3、python的源码统一声明为gbk4、使用支持中文的语料库
""""""原始数据,用于建立模型
"""
# 缩水版的courses,实际数据的格式应该为 课程名\t课程简介\t课程详情,并已去除html等干扰因素
courses = [u'Writing II: Rhetorical Composing',u'Genetics and Society: A Course for Educators',u'General Game Playing',u'Genes and the Human Condition (From Behavior to Biotechnology)',u'A Brief History of Humankind',u'New Models of Business in Society',u'Analyse Numrique pour Ingnieurs',u'Evolution: A Course for Educators',u'Coding the Matrix: Linear Algebra through Computer Science Applications',u'The Dynamic Earth: A Course for Educators',u'Tiny Wings\tYou have always dreamed of flying - but your wings are tiny. Luckily the world is full of beautiful hills. Use the hills as jumps - slide down, flap your wings and fly! At least for a moment - until this annoying gravity brings you back down to earth. But the next hill is waiting for you already. Watch out for the night and fly as fast as you can. ',u'Angry Birds Free',u'没有\它很相似',u'没有\t它很相似',u'没有\t他很相似',u'没有\t他不很相似',u'没有',u'可以没有',u'也没有',u'有没有也不管',u'Angry Birds Stella',u'Flappy Wings - FREE\tFly into freedom!A parody of the #1 smash hit game!',u'没有一个',u'没有一个2',
]# 只是为了最后的查看方便
# 实际的 courses_name = [course.split('\t')[0] for course in courses]
courses_name = courses"""预处理(easy_install nltk)
"""def pre_process_cn(courses, low_freq_filter=True):"""简化的 中文+英文 预处理1.去掉停用词2.去掉标点符号3.处理为词干4.去掉低频词"""import nltkimport jieba.analyse  # jieba分词from nltk.tokenize import word_tokenize  # 分词器texts_tokenized = []for document in courses:texts_tokenized_tmp = []for word in word_tokenize(document):texts_tokenized_tmp += jieba.analyse.extract_tags(word, 10)texts_tokenized.append(texts_tokenized_tmp)texts_filtered_stopwords = texts_tokenized# 去除标点符号,这里可以使用去除停等词的方式来处理english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']texts_filtered = [[word for word in document if not word in english_punctuations] for document intexts_filtered_stopwords]# 词干化from nltk.stem.lancaster import LancasterStemmerst = LancasterStemmer()texts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]# 去除过低频词if low_freq_filter:all_stems = sum(texts_stemmed, [])stems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)texts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]else:texts = texts_stemmedreturn textslib_texts = pre_process_cn(courses)"""引入gensim,正式开始处理(easy_install gensim)
"""def train_by_lsi(lib_texts):"""通过LSI模型的训练"""from gensim import corpora, models, similarities# 为了能看到过程日志# import logging# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)dictionary = corpora.Dictionary(lib_texts)corpus = [dictionary.doc2bow(text) for text inlib_texts]  # doc2bow(): 将collection words 转为词袋,用两元组(word_id, word_frequency)表示tfidf = models.TfidfModel(corpus)corpus_tfidf = tfidf[corpus]# 拍脑袋的:训练topic数量为10的LSI模型lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)index = similarities.MatrixSimilarity(lsi[corpus])  # index 是 gensim.similarities.docsim.MatrixSimilarity 实例return (index, dictionary, lsi)# 库建立完成 -- 这部分可能数据很大,可以预先处理好,存储起来
(index, dictionary, lsi) = train_by_lsi(lib_texts)# 要处理的对象登场
target_courses = [u'没有']
target_text = pre_process_cn(target_courses, low_freq_filter=False)"""
对具体对象相似度匹配
"""# 选择一个基准数据
ml_course = target_text[0]# 词袋处理
ml_bow = dictionary.doc2bow(ml_course)# 在上面选择的模型数据 lsi 中,计算其他数据与其的相似度
ml_lsi = lsi[ml_bow]  # ml_lsi 形式如 (topic_id, topic_value)
sims = index[ml_lsi]  # sims 是最终结果了, index[xxx] 调用内置方法 __getitem__() 来计算ml_lsi# 排序,为输出方便
sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])# 查看结果
print sort_sims[0:10]  # 看下前10个最相似的,第一个是基准数据自身
print courses_name[sort_sims[1][0]]  # 看下实际最相似的数据叫什么
print courses_name[sort_sims[2][0]]  # 看下实际最相似的数据叫什么
print courses_name[sort_sims[3][0]]  # 看下实际最相似的数据叫什么

文本分析--NLTK自然语言处理相关推荐

  1. 【自然语言处理与文本分析】自然语言处理概要

    自然语言处理的研究范畴 自然语言处理的基本流程 文本数据-->分词/词根还原-->词性标注-->[同义词标定]-->[概念标定]-->角色标定-->句法分析--&g ...

  2. 文本识别(自然语言处理,NLP)

    目录 语音识别 NLTK - 自然语言工具包 分词 词干 词形还原 词袋 词频 文档频率(DF) 逆文档频率(IDF) 词频你文档频率(TF-IDF) 基于多项分布朴素贝叶斯的情感分析 主题抽取 语音 ...

  3. 自然语言处理文本分析_通过自然语言处理释放文本分析的力量

    自然语言处理文本分析 深度学习 , 自然语言处理 (Deep Learning, Natural Language Processing) Natural language is a language ...

  4. 调用百度自然语言接口实现文本分析

    目标: 1.掌握SDK文档的使用 2.强化tkinter图像界面的编辑 ttk.Treeview()创建列表,以及树状结构 3.递归函数的使用 百度参考文档:https://ai.baidu.com/ ...

  5. 【自然语言处理与文本分析】用两个项目案例介绍文本挖掘方法论。

    文本挖掘概要 文本挖掘的应用:(有实际案例) 运用文本挖掘进行公司治理(台湾证券交易所的案例) 证券交易所的功能就是监管上市公司的问题(财务不实,内部被掏空的问题).但是会出现一个盲点 比如一家公司宣 ...

  6. python爬虫自学笔记分析解密_python爬虫学习笔记——1 各种文本分析工具简介之汇总...

    此处只简单汇总一下各种文本工具名目,他们的详细使用参见具体帖子.本文主要参考<8种目前Python使用率最高的文本处理工具>一文0.SnowNLP包 用于中文文本的处理 1.Jieba 2 ...

  7. delphi 停电文本数据丢失_NLP中的文本分析和特征工程

    语言检测,文本清理,长度测量,情绪分析,命名实体识别,n字频率,词向量,主题建模 前言 在本文中,我将使用NLP和Python解释如何分析文本数据并为机器学习模型提取特征. NLP(自然语言处理)是人 ...

  8. 构建meteor应用程序_我如何在一个月内构建一个复杂的文本分析应用程序

    构建meteor应用程序 by Jeffrey Flynt 由Jeffrey Flynt 我如何在一个月内构建一个复杂的文本分析应用程序 (How I built a complex text ana ...

  9. NLTK自然语言处理简介

    目录 安装 文本分类 结论 自然语言工具包(NLTK)提供了许多用于对文本内容执行自然语言处理(NLP)和机器学习分析的功能.我们将通过一个情感分析示例来演示其文本分类功能. 下载源1.6 KB 这是 ...

最新文章

  1. 为什么有些高级开发不喜欢 Python?
  2. 前端学习(2488):使用git获取代码
  3. python - 环境搭建
  4. leetcode 303 python(动态规划)
  5. Java社区对Java发布周期声明的反应
  6. ASP.NET MVC3 及其学习资源
  7. python多进程共享变量,附共享图像内存实例
  8. 阅读笔记10-职场黑话大全(互联网公司百科版)
  9. vasp软件全名是什么_vasp软件使用
  10. 在EXCEL中进行趋势拟合与预测的方法
  11. 贝叶斯决策论及朴素贝叶斯分类器
  12. invalid operands to binary expression 二进制表达式的无效操作数
  13. Mac如何清理应用软件
  14. 10大改变世界的未来科技
  15. Linux下的gpt分区
  16. nn.Sequential()
  17. javaweb基于SSM框架的书籍小说在线阅读下载网站
  18. 【开发指南】Spring Cloud集成POI完成Excel读写操作
  19. 穆易天气app代码(二)
  20. 计算机设备驱动的作用,驱动程序是什么意思,电脑驱动程序有什么作用!

热门文章

  1. NIST的安全内容自动化协议(SCAP)以及SCAP中文社区简介
  2. 震撼人心的战争类背景音乐
  3. Linux内核和用户空间通信的方法
  4. Beautifulsoup+正则表达式多线程爬取小姐姐图片
  5. 【雕爷学编程】Arduino动手做(79)---MQ135空气检测模块
  6. 干货分享 | GopherChina 2019北京大会PPT下载
  7. matlab 图像白平衡算法,Matlab常用白平衡算法
  8. AE制作粉笔字特效教程 3分钟快速制作Vlog片头
  9. 大数据面试题以及答案整理(面试必备)
  10. 【Unity】TimeLine常见问题:如何实现人形角色动画的平滑切换