首页 文章 精选 留言 我的

精选列表

搜索[学习],共10000篇文章
优秀的个人博客,低调大师

Java-学习笔记-4-抽象

不足之处,欢迎专家、同行、读者批评指正。 上一篇在说类库文件时提到了封装,不够严谨,这一篇来简单讲讲。 抽象和封装,这是面向对象程序设计中的一个重要思想。换句话说,是思维方式的转变。以前我们编程,是围绕某一个问题的,研究它的过程是怎样的。现在嘛,是考虑不同的对象之间的信息传递,更适合来写不同对象交互信息的业务。 先说说抽象。最关键的在于属性和功能。举个例子吧,比如说现在你要去图书馆借书,那对你来说,你的属性就是个人ID,借阅权限,借了几本书等等,图书馆那边对象很多,比如说管理员、书等等。你们之间的业务往来,就可以看作功能。 更直白点说,属性通常就是信息的那个值,编程时我们写成int的这种,所谓的功能就是对这个值进行操作的函数或者说方法。当然啦,一个类之中嵌套另一个类,并且把里边的那个类看做是成员变量,这种情况也是有的,不过在理解含义时可以把它和上文的“值”看作一回事。

优秀的个人博客,低调大师

Java-学习笔记-5-封装

不足之处,欢迎专家、同行、读者批评指正。 抽象和封装其实可以放到一起来记。 封装,字面意思看起来像是封上口打包装起来——实际上就是这个意思。只不过,这里我们打包的不是快递包裹,是代码的源文件。Java是有包管理机制的。 这个包,在资源管理器里看的话,是一个个的文件夹——但反过来不能说文件夹就是包。你看,封装,打包,命名的时候就是这么直白。 这个机制,是对访问权限的限制。不过它限制的不是我们。作为开发者,我们自己所负责的几个包中,所有代码都是可以看到的。但是,它限制了不同包的源文件中的变量或者方法,访问其他源文件中的变量或者方法的权限。 关于这个,和C++相似,但不一样。具体可以查阅文档。搜索的关键字可以是public、private等。 是的,文档永远是第一手信息。

优秀的个人博客,低调大师

Java-学习笔记-6-继承

不足之处,欢迎专家、同行、读者批评指正。 我们写代码,当然是希望越简单越好——这个简单是说简洁没有废话,但也不是极端的少,而是必须便于理解,不是秀操作的那种一行写完原本十行的逻辑,让别人读起来像做解谜游戏一样。 继承就有这个好处。 在面向对象的思想中,我们操作的是一个个的对象。如果对象之间有从属关系,我们再去写其中相同的内容,岂不是很多余?这时候就该用上继承了。 当然,继承的作用远不止如此。 继承、多态、某种角度还可能要算上接口,这些是需要打通理解的知识点。

优秀的个人博客,低调大师

Java-学习笔记-7-多态

不足之处,欢迎专家、同行、读者批评指正。 关于多态,我在学的时候遇到了不同的划分范畴的说法。一种理解是,子类对象分别各自实现父类对象的同一个方法。而我本科所用的教材,则是说这个有子类对象作为父类对象引用、子类对父类方法的覆盖、同一个类中方法的覆盖。(因为这个是之前面试时我和面试官分歧的地方,所以印象深刻,他持第一种观点,认为我提到的“同一个类中方法的覆盖”这个不是多态) 之前写了几篇文章,似乎没什么人关注。如果有人关注的话,稍后我会补上自己总结的用来理解的代码示例。

优秀的个人博客,低调大师

Java-学习笔记-8-接口

不足之处,欢迎专家、同行、读者批评指正。 Java在设计的时候为了求简,是舍弃了多继承机制的。但是,实际开发中有时候又需要用。于是,开发者们就曲线救国,通过接口来变相地实现多继承。 其实我个人也比较赞同单继承。接口和继承,是两个不同层次的概念,本来不应该相提并论的。不过在使用时,比较接近。 今天太晚了,先写到这里。如果有人关注的话,稍后我会补上更多的理解。

优秀的个人博客,低调大师

Java-学习笔记-1-概述

不足之处,欢迎专家、同行、读者批评指正。 源起 Java语言的前身是oak语言——oak是在1991年诞生于Sun公司的研究项目,由 James Goslingt 和 Patrick naughton 这两位大牛负责。这个项目最初是为了给消费级电子设备(通俗点说就是家用电器)提供一个通用的开发环境,结果并不成功。这个不成功说的是这个项目它不赚钱,不是说这个oka没开发出来。 简单说一下这个oka。一开始他们本来是打算用c++的,但是C++的安全性差。所以他们就参考C++开发了一个新语言,oak。也就是C特性的一些语法,加上安全性方面的机制。 回来接着说这个项目。正所谓乱世出英雄,这个生不逢时的oak项目,在互联网时代迎来了曙光。因为它的三大特性:跨平台、面向对象、安全性高,正好符合互联网的需要。跨平台,这个是他们一开始就设计好的,因为当初就是为了解决不同设备的通用环境问题。面向对象,这个是C++的特性。安全性,这个是他们自己补充的。但是oak不是拿来就能在Internet上直接用的,所以他们就结合互联网的需求,重新设计了一下oak,最后把它取名叫做Java——没错,就是爪哇,图标都配的是当地特产咖啡。这是在1995年,Java正式面世。 Java与C++的比较 先说它们两个的相同点:它们都是面向对象的——Java当初在设计的时候就向C++借鉴了这一点。所以他们在语法上也非常相似。 接下来再说说它们的不同点。它们最大的不同就是:Java不支持指针,而C++是支持指针的。指针对于编程新手来说,非常的不友好。甚至可能在开发的过程中造成严重的后果。而Java由于不支持指针,从一开始就限制了程序员不能使用指针,主动避免了这个问题。所以说Java比C++简单了很多。这也是Java广受欢迎,应用广泛的原因之一。 第二个不同点。Java 需要被编译成虚拟机的字节码,通过虚拟机来运行。而C++则是直接编译成机器码,然后直接运行。由此可以看出,Java的运行效率是不如C++的。 第三个不同点。Java 中最基本的数据类型都有规定的字节大小。而C++中数据类型的字节大小,要看它具体是怎么实现的。Java中所有对象都是按引用传递的。而C++中的对象都是按值传递的。 第四个不同点。C++保留了许多 C 的功能,这些是面向底层的。Java 中去除了这些功能。同时,Java 用垃圾回收代替了程序员自己释放内存,还放弃了运算符重载和多重继承等这些c++的功能。但在Java的实际编程操作中,我们可以利用接口来实现有限制的多重继承。 第五个不同点。Java更关注的是安全性,可移植性和快速开发。C++则是关注性能和对C向下兼容。

优秀的个人博客,低调大师

机器学习实例-titanic数据预处理

加载数据集,打印前五行: import numpy as np import pandas as pd import seaborn as sns from scipy import stats,integrate import matplotlib.pyplot as plt %matplotlib inline data=pd.read_csv("Desktop/titanic_train.csv") print(data.head()) PassengerId Survived Pclass \0 1 0 3 1 2 1 1 2 3 1 3 3 4 1 1 4 5 0 3 Name Sex Age SibSp \ 0 Braund, Mr. Owen Harris male 22.0 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 2 Heikkinen, Miss. Laina female 26.0 0 3 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 4 Allen, Mr. William Henry male 35.0 0 Parch Ticket Fare Cabin Embarked 0 0 A/5 21171 7.2500 NaN S 1 0 PC 17599 71.2833 C85 C 2 0 STON/O2. 3101282 7.9250 NaN S 3 0 113803 53.1000 C123 S 4 0 373450 8.0500 NaN S 查看原始数据统计结果: print(data.describe()) PassengerId Survived Pclass Age SibSp \count 891.000000 891.000000 891.000000 714.000000 891.000000 mean 446.000000 0.383838 2.308642 29.699118 0.523008 std 257.353842 0.486592 0.836071 14.526497 1.102743 min 1.000000 0.000000 1.000000 0.420000 0.000000 25% 223.500000 0.000000 2.000000 20.125000 0.000000 50% 446.000000 0.000000 3.000000 28.000000 0.000000 75% 668.500000 1.000000 3.000000 38.000000 1.000000 max 891.000000 1.000000 3.000000 80.000000 8.000000 Parch Fare count 891.000000 891.000000 mean 0.381594 32.204208 std 0.806057 49.693429 min 0.000000 0.000000 25% 0.000000 7.910400 50% 0.000000 14.454200 75% 0.000000 31.000000 max 6.000000 512.329200 可以看到Age这一项有缺失值。 填充缺失值有很多种方法,最常见的比如说均值填充,中位数填充,等等。 首先看一下年龄数据的原始分布状况: sns.distplot(data["Age"].dropna(),kde=True,bins=50,fit=stats.gamma)#dropna()处理浮点数据 先用均值填充: data["Age"]=data["Age"].fillna(data["Age"].mean()) sns.distplot(data["Age"].dropna(),kde=True,bins=50,fit=stats.gamma) 可以明显看到图像已经变形,虽然也可以用均值填充的数据进行训练,但如果可以改进填充方式,就可以使数据分布更接近实际。 于是我们提取一些与年龄相关的特征,比如船票(年轻人通常比较穷,富人年纪大),家庭成员数量,兄弟姐妹数量,船舱等级等。 在正式训练数据前,先通过线性回归大致预测一下年龄缺失的部分人的年龄。 print(age_df.head(10)) Age Fare Parch SibSp Pclass0 22.000000 7.2500 0 1 31 38.000000 71.2833 0 1 12 26.000000 7.9250 0 0 33 35.000000 53.1000 0 1 14 35.000000 8.0500 0 0 35 27.525206 8.4583 0 0 36 54.000000 51.8625 0 0 17 2.000000 21.0750 1 3 38 27.000000 11.1333 2 0 39 14.000000 30.0708 0 1 2 可以看到,船票价格相比其他数据非常高,先对船票价格进行标准化处理 #标准化 from sklearn import preprocessing age_df=data[["Age","Fare","Parch","SibSp","Pclass"]].copy()#.copy()用于复制原始数据,否则在为DataFrame对象新增一列数据时会报错“A value is trying to be set on a copy of a slice from a DataFrame.” #scaler=preprocessing.StandardScaler() #age_df["Fare_scaled"]=scaler.fit_transform(age_df.loc[:,"Fare"])#数据维数问题出错了,暂不知如何解决 age_df["Fare_scaled"] = preprocessing.scale(age_df.loc[:,"Fare"]) print(age_df.head(10)) del age_df["Fare"] Age Fare Parch SibSp Pclass Fare_scaled0 22.000000 7.2500 0 1 3 -0.5024451 38.000000 71.2833 0 1 1 0.7868452 26.000000 7.9250 0 0 3 -0.4888543 35.000000 53.1000 0 1 1 0.4207304 35.000000 8.0500 0 0 3 -0.4863375 27.525206 8.4583 0 0 3 -0.4781166 54.000000 51.8625 0 0 1 0.3958147 2.000000 21.0750 1 3 3 -0.2240838 27.000000 11.1333 2 0 3 -0.4242569 14.000000 30.0708 0 1 2 -0.042956 数据处理结束,分割数据集: #分割有缺失值的数据集 known_age=age_df[age_df.Age.notnull()] unknown_age=age_df[age_df.Age.isnull()] #print(known_age.head()) x=known_age.iloc[:,1:] y=known_age.iloc[:,0] x_test=unknown_age.iloc[:,1:] y_pred=unknown_age.iloc[:,0] 训练模型,预测结果,填充缺失值: from sklearn import linear_model lr = linear_model.LinearRegression() model=lr.fit(x,y) y_pred=lr.predict(x_test) data.loc[data.Age.isnull(),"Age"]=y_pred sns.distplot(data["Age"].dropna(),kde=True,bins=50,fit=stats.gamma) 填充结果如上图,相比均值填充,通过模型填充缺失值得到了更符合真实分布的数据。

优秀的个人博客,低调大师

NLTK基础教程学习笔记(十三)

在信息摘要应用中还包含着另一种理论逻辑:重要的句子中通常包含着重要的词汇,而跨语料库的差异词(discriminatory word)绝大多数数是重要词汇。因此,句子中包含具有差异很大的词汇,它就很重要。这样就得到一个非常简单的测量方法,就是计算每一个词各种的TF-IDF(term frequency-inverse document )分值,然后根据词汇的重要性找出一种标准化的凭据评分。这个评分就可以用来充当在信息摘要中选取句子的标准。 TF-IDF(term frequency–inverse document frequency)是一种用于资讯检索与资讯探勘的常用加权技术。TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。TF-IDF加权的各种形式常被搜寻引擎应用,作为文件与用户查询之间相关程度的度量或评级。除了TF-IDF以外,因特网上的搜寻引擎还会使用基于连结分析的评级方法,以确定文件在搜寻结果中出现的顺序。按照其不拿整段介绍来做,只拿前三句来实践,我拿了前一段: import nltk from sklearn.feature_extraction.text import TfidfVectorizer f=open('news.txt') news_content=f.read() results=[] sentences=nltk.sent_tokenize(news_content) vectorizer=TfidfVectorizer(norm='l2',min_df=0,use_idf=True,smooth_idf=False,sublinear_tf=True) sklearn_binary=vectorizer.fit_transform(sentences) print(vectorizer.get_feature_names()) print(sklearn_binary.toarray()) 结果: ['accept', 'accepting', 'altria', 'and', 'announce', 'approaches', 'arthur', 'as', 'at', 'be', 'birth', 'britain', 'british', 'by', 'caliburn', 'ceremonial', 'character', 'decides', 'despite', 'destined', 'dies', 'draws', 'ector', 'eligible', 'embedded', 'enters', 'entrusted', 'explaining', 'fearing', 'fifteen', 'following', 'for', 'full', 'gender', 'growing', 'hardships', 'heir', 'her', 'hesitation', 'his', 'however', 'if', 'in', 'inspired', 'invasion', 'is', 'king', 'knight', 'known', 'large', 'leadership', 'leaving', 'legends', 'legitimate', 'loyal', 'mantle', 'merlin', 'monarch', 'name', 'nativity', 'never', 'no', 'not', 'of', 'or', 'pendragon', 'people', 'period', 'preserving', 'publicly', 'pulling', 'raises', 'recognize', 'responsible', 'ruler', 'saber', 'saxons', 'she', 'shoulders', 'sir', 'slab', 'son', 'soon', 'stone', 'subjects', 'surrogate', 'sword', 'symbolic', 'that', 'the', 'this', 'threat', 'throne', 'to', 'turmoil', 'uther', 'welfare', 'when', 'who', 'will', 'withdraws', 'without', 'woman'] [[ 0. 0. 0.15095332 0. 0. 0. 0.31622502 0. 0. 0. 0. 0. 0. 0.20340954 0. 0. 0.31622502 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.31622502 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.31622502 0. 0.17386773 0.24504638 0. 0. 0. 0. 0. 0.31622502 0. 0. 0. 0. 0. 0.31622502 0. 0. 0. 0. 0.15095332 0. 0.31622502 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.31622502 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.15095332 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0.23250474 0. 0.11098857 0. 0.23250474 0. 0. 0.14955705 0.23250474 0. 0.23250474 0. 0. 0. 0. 0. 0. 0.23250474 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.23250474 0. 0. 0. 0. 0.18017058 0. 0. 0. 0.11098857 0. 0.23250474 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.23250474 0. 0. 0. 0. 0. 0.23250474 0.23250474 0. 0.23250474 0. 0.23250474 0. 0. 0. 0. 0.23250474 0. 0. 0. 0. 0.18017058 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.23250474 0. 0. 0. 0. 0. 0. 0. 0. 0.14955705 0. 0.18017058 0. 0. 0. 0.14955705 0. 0. 0.23250474] [ 0. 0. 0. 0. 0. 0. 0. 0.18736875 0. 0. 0. 0. 0. 0.18736875 0. 0. 0. 0. 0. 0. 0. 0. 0.29128766 0. 0. 0. 0.29128766 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.13904921 0. 0. 0. 0. 0. 0. 0. 0.1601566 0. 0.29128766 0. 0. 0. 0. 0. 0. 0.29128766 0. 0.22572213 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.29128766 0. 0. 0. 0. 0. 0.18736875 0. 0.29128766 0. 0.29128766 0. 0. 0. 0.29128766 0. 0. 0. 0. 0. 0. 0. 0.18736875 0. 0. 0. 0. 0.29128766 0. 0. 0. 0. ] [ 0. 0. 0.14155101 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.29652856 0. 0. 0.29652856 0. 0. 0. 0. 0. 0.29652856 0. 0. 0. 0. 0. 0. 0.29652856 0. 0. 0. 0. 0. 0. 0. 0. 0.16303816 0.22978336 0. 0.29652856 0. 0. 0.29652856 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.29652856 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.14155101 0. 0. 0.29652856 0.19073992 0. 0.22978336 0. 0.29652856 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.24121053 0. 0.20022545 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.31127497 0. 0. 0. 0. 0.31127497 0. 0. 0. 0.31127497 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.31127497 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.25158536 0. 0. 0. 0.31127497 0. 0. 0. 0. 0. 0. 0. 0. 0.31127497 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.25158536 0. 0.31127497 0. 0. 0.31127497 0. 0. 0. 0. 0. 0. 0. 0. ] [ 0. 0. 0.10632924 0. 0. 0.22274414 0. 0.14327861 0. 0. 0. 0. 0.22274414 0. 0.17260697 0.22274414 0. 0. 0. 0.22274414 0. 0. 0. 0. 0.22274414 0. 0. 0.22274414 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.10632924 0. 0. 0. 0.22274414 0.22274414 0. 0. 0. 0. 0. 0. 0.22274414 0. 0. 0. 0. 0. 0. 0.17260697 0. 0. 0. 0. 0. 0. 0.10632924 0. 0. 0.17260697 0. 0. 0. 0. 0. 0.22274414 0. 0.17260697 0. 0. 0.14327861 0. 0. 0.22274414 0. 0.22274414 0.22274414 0. 0. 0.17260697 0. 0.22274414 0.10632924 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.14327861 0.22274414 0. 0. ] [ 0. 0.24521796 0.11705736 0.19002219 0. 0. 0. 0. 0. 0.24521796 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.24521796 0. 0. 0. 0.24521796 0. 0.11705736 0. 0. 0.24521796 0. 0. 0. 0. 0.13482643 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.24521796 0. 0. 0. 0. 0. 0.24565801 0. 0. 0.19002219 0. 0.24521796 0. 0.24521796 0. 0. 0.24521796 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.19002219 0.24521796 0. 0.19819534 0.24521796 0. 0. 0. 0. 0. 0.24521796 0. 0. 0.15773474 0. 0. 0. ] [ 0. 0. 0. 0.38872173 0. 0. 0. 0. 0. 0. 0. 0.22958532 0. 0. 0.22958532 0. 0. 0. 0.29627299 0. 0. 0.29627299 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.22958532 0. 0. 0. 0.14142901 0.29627299 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.29627299 0. 0. 0. 0. 0.29627299 0. 0. 0. 0. 0. 0. 0. 0.14142901 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.19057553 0.29627299 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.29627299 0. ]]

优秀的个人博客,低调大师

NLTK基础教程学习笔记(十二)

构建第一个NLP应用:信息摘要:对所提供的文章短文故事生成需要针对其内容自动生成摘要。信息摘要需要理解的不只是句子的结构,而是整个文本结构,还要了解文本的体裁和主体主题内容。下面了一个介绍创建个人版的Google News通常用于较多实体和名词的句子的重要性往往会比较高,现在的任务是要用某种可能被标准化的统一逻辑来计算重要性成分(importance score),即如果想要获取前n个句子的信息情况,要去选择一个重要性评分阈值。由于找不到原文的新闻材料所以用wiki上的一段介绍吾王Saber材料代替; f=open('new.txt','r') new_content=f.read() print(new_content) 结果: Saber's full name is Altria Pendragon, a character inspired by the legends of King Arthur. At her nativity, Uther decides to not publicly announce Altria's birth or gender, fearing his subjects will never accept a woman as a legitimate ruler. She is entrusted by Merlin to a loyal knight, Sir Ector, who raises her as a surrogate son. When Altria is fifteen, King Uther dies leaving no known eligible heir to the throne. Britain enters a period of turmoil following the growing threat of invasion by the Saxons. Merlin soon approaches Altria, explaining that the British people will recognize her as a destined ruler if she withdraws Caliburn, a ceremonial sword embedded in a large slab of stone. However, pulling this sword is symbolic of accepting the hardships of a monarch, and Altria will be responsible for preserving the welfare of her people. Without hesitation and despite her gender, she draws Caliburn and shoulders Britain's mantle of leadership. Altria rules Britain from her stronghold in Camelot and earns the reputation of a just, yet distant king. Under the guidance of Merlin and with the aid of her Knights of the Round Table, she guides Britain into an era of prosperity and tranquillity. Caliburn is destroyed, but Altria soon acquires her holy sword, Excalibur, and Avalon, Excalibur's blessed sheath, from Vivian, the Lady of the Lake. While Avalon is in her possession, Altria never ages and is immortal in battle. Despite her immense strength and fighting abilities, Altria is plagued by feelings of guilt and inferiority throughout her reign; she sacrifices her emotions for the good of Britain, yet many of her subjects and knights become critical of her lack of humanity and cold calculation. Excalibur's scabbard is stolen while she repels an assault along her country's borders; when Altria returns inland, she discovers Britain is being torn asunder by civil unrest. Despite her valiant efforts to placate the dissent, Altria is mortally wounded by a traitorous knight, a homunculus born of her blood named Mordred, during the Battle of Camlann. Her dying body is escorted to a holy isle by Morgan le Fay and Sir Bedivere. Altria orders a grieving Bedivere to dispose of Excalibur by throwing it back to Vivian; in her absence, she reflects on her personal failures, regretting her life as king. Before her last breath, she appeals to the world; in exchange for services as a Heroic Spirit, she asks to be given an opportunity to relive her life, where someone more suitable and effective would lead Britain in her stead. 要对文字进行分析,先要将文章转换成一个句子列表。用句子标识器将内容分成若干个句子,这里提供一些句型的编号,便于识别这些句子并对其进行排名。一旦得到了这些段子,会让其在单词标识器中过一遍,最后再来过NER标注器和POS标注器。 import nltk f=open('new.txt','r') new_content=f.read() results=[] for sent_no,sentence in enumerate(nltk.sent_tokenize(new_content)): no_of_tokens=len(nltk.word_tokenize(sentence)) #print(no_of_tokens) tagged=nltk.pos_tag(nltk.word_tokenize(sentence)) no_of_nouns=len([word for word ,pos in tagged if pos in ["NN","NNP"]]) ners=nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sentence))) no_of_ners=len([chunk for chunk in ners if hasattr(chunk,'label')]) score=(no_of_ners+no_of_nouns)/float(no_of_tokens) results.append((sent_no,no_of_tokens,no_of_ners,no_of_nouns,score,sentence)) for sent in sorted(results,key=lambda x:x[4],reverse=True): print(sent[5]) 上面代码中我们对句子列表进行了迭代,并根据公式计算出了这些句子的评分,该公式只是个以被标识实体为分子,以普通标识词为分母的分子式,将这些结果创建成一个元组。降序排列后打印的结果: Caliburn is destroyed, but Altria soon acquires her holy sword, Excalibur, and Avalon, Excalibur's blessed sheath, from Vivian, the Lady of the Lake. Her dying body is escorted to a holy isle by Morgan le Fay and Sir Bedivere. Saber's full name is Altria Pendragon, a character inspired by the legends of King Arthur. Britain enters a period of turmoil following the growing threat of invasion by the Saxons. Altria rules Britain from her stronghold in Camelot and earns the reputation of a just, yet distant king. Without hesitation and despite her gender, she draws Caliburn and shoulders Britain's mantle of leadership. Under the guidance of Merlin and with the aid of her Knights of the Round Table, she guides Britain into an era of prosperity and tranquillity. While Avalon is in her possession, Altria never ages and is immortal in battle. Excalibur's scabbard is stolen while she repels an assault along her country's borders; when Altria returns inland, she discovers Britain is being torn asunder by civil unrest. Despite her valiant efforts to placate the dissent, Altria is mortally wounded by a traitorous knight, a homunculus born of her blood named Mordred, during the Battle of Camlann. When Altria is fifteen, King Uther dies leaving no known eligible heir to the throne. She is entrusted by Merlin to a loyal knight, Sir Ector, who raises her as a surrogate son. Merlin soon approaches Altria, explaining that the British people will recognize her as a destined ruler if she withdraws Caliburn, a ceremonial sword embedded in a large slab of stone. Altria orders a grieving Bedivere to dispose of Excalibur by throwing it back to Vivian; in her absence, she reflects on her personal failures, regretting her life as king. At her nativity, Uther decides to not publicly announce Altria's birth or gender, fearing his subjects will never accept a woman as a legitimate ruler. Before her last breath, she appeals to the world; in exchange for services as a Heroic Spirit, she asks to be given an opportunity to relive her life, where someone more suitable and effective would lead Britain in her stead. Despite her immense strength and fighting abilities, Altria is plagued by feelings of guilt and inferiority throughout her reign; she sacrifices her emotions for the good of Britain, yet many of her subjects and knights become critical of her lack of humanity and cold calculation. However, pulling this sword is symbolic of accepting the hardships of a monarch, and Altria will be responsible for preserving the welfare of her people. 完成了句子的排序,一旦有no_of_nouns和no_of_ners的评分列表,就可以围绕他们建议一些更加复杂的规则。

优秀的个人博客,低调大师

NLTK基础教程学习笔记(十)

依赖性文本解析:依赖性文本解析(dependency parsing 简称DP)是一种现代化的文本解析机制。DP的主要概念是将各个语法单元(单词)用丁香链路串联起来。这种链路称为依赖关系(dependencies)。在目前的文本解析社区中,有大量工作在进行。尽管短语结构式文本解析(phrase structure parsing)在异乡词序自由的语言(如捷克语和土耳其语)中被广泛使用,但依赖性文本解析别被证明是一种更为有效地方法。短语结构式文本解析与依赖性文本解析之间存在着一个明显的区别,从他们所产生的解析树上可以看出来。解析书上短语结构树试图捕捉的首先是单词与短语之间的关系,然后是短语与短语之间的关系,依存关系树只关心单词与单词之间的关系如big完全依赖于dog。NLTK库也提供了一些可用于执行依存性文本解析的方法。其中一个是使用基于概率的投射依存性解析器(probabilistic,projective dependency parser),但解析器得经由某个有限训练数据集来进行训练。依存性解析器的另一种形态就是Stanford解析器。下面是一个Stanford解析器的例子:语块分解:语块分解属于浅解析,目的是将句子分解成有意义的语块,将语块定义为文本解析中的最小单元,例如将“the President speaks about the health care reforms “句子分成两个语块。第一个语块“the President”该语块由名词主导,称为名词短语(NP),另一部分由动词主导称为动词短语。将句子划分成各个部分的过程就是语块分解。从形式上看语块分解操作也可以被看作是一种处理接口,作用是识别出文本中互相不重叠的部分。对于一些文本问题想只想提取其中的关键短语,命名实体或者先关项目的特定模式,在这种情况下要做浅解析非深解析,深解析回去处理所有违法语法规则的句子,也会产生不同的语法树,直到解析器在反复回溯的过程中找到最佳的解析树,整个过程非常耗时和繁琐,并且完成了所有的这些过程也未必会得到正确的解析树。而浅解析则可以用语块来保证其浅解析的结构,这种处理相对而言要较快一些。

优秀的个人博客,低调大师

NLTK基础教程学习笔记(六)

用NLYK库实现标注任务的方式有两种:1:使用NLTK库或其他库中的预置标注器,并将其运用到测试数据上。这两种标注器应该足以应对英语文本环境,以及非特殊领域语料库中的所有词性标注任务。2:基于测试数据来创建或训练出适合的标注器。深入了解标注器:一个典型的标注器通常要用到大量的训练数据,它主要被用于标注出句子中的各种单词,并为其贴上POS标签。标注是一个纯手工的工作,具体如下: Well/UH what/WP do/VBP you/PRP think/VB about/IN the/DT idea/NN of/IN... 以上是来自Penn Treebank的语义库。其中还有一个语言数据联盟(LDC)专门用来研究不同语言的标注,不同文本种类以及不同标注操作,如词性标注,句法分析标注,以及对话标注等。通常情况下,像词性标注这样的标注问题往往会被视为顺序标签化的问题或者某种分类问题,后者特指人们为特定token所生成的正确标签,并用先关判别模型对其进行判别的一类问题。下面是分析Brown语料库中各POS标签的分布频率: from nltk.corpus import brown import nltk tags=[tag for (word,tag)in brown.tagged_words(categories='news')] print(nltk.FreqDist(tags)) out=nltk.FreqDist(tags) 结果: <FreqDist with 218 samples and 100554 outcomes> 由于个数太多无法打印,可以通过debug进去看各个词的的频率。Debug进去看可以看到NN在这里出现频率最高,可以用来创建一个POS标注器,用来给所有的测试文本分配NN标签。DefaultTagger函数是顺序性标注器,标注器会去调用evaluate()函数,该函数主要用来评估相关单词POS的准确度,是对Brown语料库的标注器所用的基准: from nltk.corpus import brown import nltk brown_tagged_sents=brown.tagged_sents(categories='news') default_tagger=nltk.DefaultTagger('NN') print(default_tagger.evaluate(brown_tagged_sents)) 结果: 0.13089484257215028 准确率大概13%左右DefaultTagger的表现并不是很好,DefaultTagger本质上只是基类SequentialBackoffTagger的一部分,后者是一个顺序性标注服务。标注器会试着基于其所处的上下文环境来模型化先关的标签。而且如果它不能进行正确的标签预测,就会去咨询BackoffTagger。通常情况下,DefaultTagger参数都可以被当作一个BackoffTagger实体来使用。N-gram标注器 from nltk.tag import UnigramTagger from nltk.tag import DefaultTagger from nltk.tag import BigramTagger from nltk.tag import TrigramTagger from nltk.corpus import brown import nltk brown_tagged_sents=brown.tagged_sents(categories='news') default_tagger=nltk.DefaultTagger('NN') train_data=brown_tagged_sents[:int(len(brown_tagged_sents)*0.9)] test_data=brown_tagged_sents[int(len(brown_tagged_sents)*0.9):] unigram_tagger=UnigramTagger(train_data,backoff=default_tagger) print(unigram_tagger.evaluate(test_data)) bigram_tagger=BigramTagger(train_data,backoff=unigram_tagger) print(bigram_tagger.evaluate(test_data)) trigram_tagger=TrigramTagger(train_data,backoff=bigram_tagger) print(trigram_tagger.evaluate(test_data)) 结果: 0.8368384331705372 0.8460081730290043 0.8439150802352238 其中,基于元模型的标注只考虑相关标签的条件概率,以及针对每个给定token所能预测到的、频率最高的标签。而bigram-tagger参数将会考虑给定的单词和该单词的前一个单词,其标签将以元组的形式来关联被测试单词所得到的标签。类似的,TrigramTagger参数将让其查找过程兼顾到给定单词的前两个单词。TrigramTagger参数的覆盖范围比较小,而实例精度则高一些。从另一方面来说,UnigramTagger的覆盖范围则会大一些。为了让准确率和反馈率之间保持平衡,上述代码结合了这三种标注器。

优秀的个人博客,低调大师

NLTK基础教程学习笔记(四)

标识化处理:机器所要理解的最小处理单位是单词(分词)。标识化处理,是将原生字符创分割成一系列有意义的分词。标识化就是将原生字符串分割成一系列有意义的分词。标识化处理的复杂性因具体NLP应用而异,目标语言本身的复杂性本身也会带来相关的变化。在英语中,可以通过正则表达式简单的单词来选取纯单词和数字,但在中文中会成为一个复杂的任务 from nltk.tokenize import word_tokenize from nltk.tokenize import regexp_tokenize,wordpunct_tokenize,blankline_tokenize s="Hi Everyone! hola gr8" print(s.split()) print(word_tokenize(s)) print(regexp_tokenize(s,pattern='\w+')) print(regexp_tokenize(s,pattern='\d+')) print(wordpunct_tokenize(s)) print(blankline_tokenize(s)) 结果: ['Hi', 'Everyone!', 'hola', 'gr8'] ['Hi', 'Everyone', '!', 'hola', 'gr8'] ['Hi', 'Everyone', 'hola', 'gr8'] ['8'] ['Hi', 'Everyone', '!', 'hola', 'gr8'] ['Hi Everyone! hola gr8'] 上面用到了各种标识器(tokenizer)Python字符串类型方法split():是一个最基本的标识器,使用空白符来执行单词的分割,split()本身也可以被配置成为一些较为复杂的标识化处理。word_tokensize()方法是一个通用的,强大的,面向对象的可面向对象所有类型预料库的标识化处理方法。regex_tokensize()是一个位用户需求设计的,自定义程度更高的表示器,如用可以基于正则表达式的标识器分割出相同的字符串,用/w分割出单词和数字用/d对数字进行提取词干提取:词干提取(stemming)是一个修枝剪叶的过程,通过一些基本的规则,可以得到所有的分词。词干提取是一种较为粗糙的过程,希望用它来取得相关的分词的各种变化,如eat这个词会有像eating,eaten,eats等变化。在某些情况下不需要区别这些,通常会用词干提取的方法将这些变化归结为相同的词根。对于简单的方法我们可以用词干提取,对于较为复杂的NLP问题,我们必须改用词形还原(lemmatization):下面是一个词干提取的例子: from nltk.stem import PorterStemmer from nltk.stem.lancaster import LancasterStemmer from nltk.stem.snowball import SnowballStemmer pst=PorterStemmer() lst=LancasterStemmer() print(lst.stem("eating")) print(pst.stem("shopping")) 结果: eat shop 一个拥有基本规则的词干提取器,在像移除-s/es、-ing或-ed这里事情上都可以达到70%的精确度。Poster1和lancaStemmer有更多的规则,精确度会更加高。当多种词干提取算法介入时,精确度和性能上会有差异。Snowball能处理荷兰语,英语,法语,德语,意大利语,葡萄牙语,罗马尼亚语和俄语等语言。词形还原:词形还原(lemmatization)涵盖了词根所有的文法和变化形式,还会利用上下文语境和词性来确定相关单词的变化,并运用不同的标准化规则,根据词性来获取相关的词根。 from nltk.stem import WordNetLemmatizer wlem=WordNetLemmatizer() print(wlem.lemmatize("ate")) 结果 ate WordNetLemmatizer使用了wordnet,会针对某个单词去搜索wordnet这个语义字典,还用到了变形分析,以便直切词根并搜索到特殊词形。停用词移除:停用词移除(Stop word removal)简单的移除预料库中在所有文档中可能出现的单词,通常是冠词和代词。 from nltk.corpus import stopwords stoplist=stopwords.words('english') #print(stoplist) text="This is just a test" out=cleanwordlist=[word for word in text.split() if word not in stoplist] print(out) 结果: ['This', 'test']

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册