python 基础练习题

合集下载

python基础练习题30道

python基础练习题30道

python基础练习题30道1、执⾏python脚本的两种⽅式答:1>可以在python /home/xxxx.py2>cd /home ./xxxx.py 因为py脚本⾥⾯指定了python解释器的位置2、简述位、字节的关系答:1Byte(字节)=8bit(⼆进制位)3、简述ascii、unicode、uft-8、gbk的关系答:ascii 英⽂编码,8个⼆进制位代表⼀个字母,总共可以有2的8次⽅减去1个等于255个gbk是中⽂编码,是⽤的16个⼆进制代表⼀个汉字,有点浪费空间uft-8也是中⽂编码,也是⽤的16个⼆进制代表⼀个汉字,但是能⽤8位表⽰就⽤位了4、请写出“李杰”分别⽤utf-8的gbk编码所占的位数6 45、python单⾏注释和多⾏注释分别⽤什么?答:单⾏注释⽤# 多⾏注释⽤""" """6、声明变量注意事项有哪些?答:变量 = "abc" 变量空格 = 空格双引号之间的字符就是变量,在调⽤的时候要⽤吧变量⽤括号括起来()变量,只能由字母、数字、下划线组成特例:不能以数字开头python的关键字也不能使⽤7、如有以下变量n1 = 5,请使⽤int提供的⽅法,得到该变量最少可以⽤多少个⼆进制位表⽰答:n1 = 5v = n1.bit_length()print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py38、布尔值分别有什么?答:True False9、阅读代码,请写出执⾏结果a = "gouguoqi"b = a.capitalize()print (a)print (b)结果是gouguoqiGouguoqi10、写代码,有如下变量,请按照要求实现每个功能a.移除name变量对应值的两边的空格,并输出移除后的内容name = " gouguoQ"v = name.strip()print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py gouguoQb.判断name变量对应的值是否以"go"开头,并输出结果name = " gouguoQ"v = name.startswith('go')print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py Falsec.判断name变量对应的值是否以"Q"结尾,并输出结果name = " gouguoQ"v = name.endswith('Q')print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py Trued.将name变量对应的值中的"o",替换为"p",并输出结果name = " gouguoQ"v = name.replace('g','p')print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py poupuoQe.将name变量对应的值根据"o"分割,并输出结果name = " gouguoQ"v = name.split('o')print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py [' g', 'ugu', 'Q']f.请问上⼀题分割之后得到的值是什么类型(可选)列表g.将name变量对应的值变⼤写,并输出结果name = " gouguoQ"v = name.upper()print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py GOUGUOQh.将name变量对应的值变成⼩写,并输出结果name = " gouguoQ"v = name.lower()print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py gouguoqi.请输出name变量对应的值的第⼆个字符?name = " gouguoQ"v = name[2]print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py oj.请输出name变量对应的值的前三个字符name = " gouguoQ"v = name[0:3]print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.pygoh.请输出name变量对应值的后2个字符name = " gouguoQ"v = name[-2:]print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.pyoQl.请输出name变量中的值"Q的索引的位置name = " gouguoQ"v = len(name)for n in range(v):if (name[n]) != "Q":continueelse:print (n,name[n])C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py7 Qm.获取⼦序列,仅不包含最后⼀个字符,如:woaini则获取woain root则获取roo name = " gouguoQ"print (name[0:-1])C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.pygouguo21、字符串是否可以迭代对象?如果可以请使⽤for循环每⼀个元素?for n in"woaini":print (n)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py woaini只要能被for循环,这个值就是可迭代对象#类,类型str各种⽅法......#对象,根据str类型创建⼀个对象,S1,在shell我们就叫变量S1 = "gouguoqi"22、请⽤代码实现a.利⽤下划线将列表的每⼀个元素拼接成字符串 li = "gouguoqi"li = "gouguoqi"v = "_".join(li)print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py g_o_u_g_u_o_q_ib.利⽤下划线将列表的每⼀个元素拼接成字符串 li = ['gou','guo','qi'] li = ['gou','guo','qi']v = "_".join(li)print (v)C:\python35\python3.exe D:/pyproject/day11数据类型的⽅法/str-way.py gou_guo_qi23、在python2和3中range有啥区别在python2.7⾥⾯,range可以直接帮我们打印出来范围内的数字,这个就有缺点了,⽐如我打印出来1万个数字,它得先把⼀万个数字打印出来,这个时候我们得等着了。

python基础测试题

python基础测试题

python基础测试题一、选择题1、以下哪个是 Python 中的合法变量名?()A 123varB var 123C my_varD @var答案:C解析:在 Python 中,变量名只能包含字母、数字和下划线,且不能以数字开头。

选项 A 以数字开头,选项 B 中间有空格,选项 D 以特殊字符@开头,都不符合变量名的规则,只有选项 C 是合法的变量名。

2、以下代码的输出结果是什么?()```pythonx = 5y = 2print(x // y)```B 2C 3D 7答案:B解析:在Python 中,`//`是整除运算符,返回商的整数部分。

5 除以 2 的商为 25,取整数部分为 2,所以输出结果是 2。

3、以下哪个方法可以将字符串转换为整数?()A `str()`B `int()`C `float()`D `complex()`答案:B解析:`int()`函数用于将一个数字或字符串转换为整数。

`str()`函数将对象转换为字符串,`float()`函数将对象转换为浮点数,`complex()`函数用于创建复数。

4、以下哪个是 Python 中用于创建列表的符号?()A `{}`B `()`D `<>`答案:C解析:在 Python 中,使用方括号``来创建列表。

花括号`{}`用于创建字典,小括号`()`用于创建元组等。

5、以下代码的输出结果是什么?()```pythonmy_list = 1, 2, 3, 4, 5print(my_list1:4)```A `2, 3, 4`B `1, 2, 3`C `2, 3, 4, 5`D `1, 2, 3, 4`答案:A解析:列表的切片操作`start:end` 会返回从索引`start` (包含)到索引`end` (不包含)的子列表。

在这个例子中,`my_list1:4` 会返回索引 1 到索引 3 的元素,即`2, 3, 4` 。

二、填空题1、 Python 中的注释可以使用_____(单行注释)和_____(多行注释)。

python基础试题

python基础试题

python基础试题一、选择题1. 在Python中,用于表示字符串的变量类型是:A. intB. floatC. strD. list2. 下列哪个选项是Python的内置数据类型?A. StackB. ArrayC. TupleD. Graph3. 在Python中,如何正确定义一个函数?A. def my_function():B. function my_function():C. MyFunction = function()D. _my_function()4. 下列哪个是Python的循环结构?A. forB. nextC. do-whileD. switch-case5. 在Python中,如何实现从1加到100的累加和?A. sum(1, 100)B. sum = 0; for i in range(1, 101): sum += iC. addUp(1, 100)D. 1.to(100).sum()二、填空题1. 在Python中,可以使用 ______ 来创建一个新的列表,例如:`[1, 2, 3]`。

2. 如果想要在Python中导入模块,需要使用 ______ 语句。

3. 在Python中,可以使用 ______ 语句来实现条件判断。

4. 对于字符串“Hello, World!”,如果想要截取从第7个字符开始到结束的所有字符,可以使用 ______ 切片操作。

5. 在Python中,定义一个名为`my_dict`的字典,其键为`'name'`,值为`'Kimi'`,应使用 ______ 语法。

三、判断题1. 在Python中,每个语句的结束都需要使用分号(`;`)。

()2. Python是一种静态类型语言。

()3. 使用`print`函数可以在Python中输出信息到控制台。

()4. 在Python中,可以使用`len`函数来获取一个列表的长度。

Python基础训练100题

Python基础训练100题

Python3基础训练100题文章目录实例001:数字组合实例002:“个税计算”实例003:完全平方数实例004:这天第几天实例005:三数排序实例006:斐波那契数列实例007:copy实例008:九九乘法表实例009:暂停一秒输出实例010:给人看的时间实例011:养兔子实例012:100到200的素数实例013:所有水仙花数实例014:分解质因数实例015:分数归档实例016:输出日期实例017:字符串构成实例018:复读机相加实例019:完数实例020:高空抛物实例021:猴子偷桃实例022:比赛对手实例023:画菱形实例024:斐波那契数列II实例025:阶乘求和实例026:递归求阶乘实例027:递归输出实例028:递归求等差数列实例029:反向输出实例030:回文数实例031:字母识词实例032:反向输出II实例033:列表转字符串实例034:调用函数实例035:设置输出颜色实例036:算素数实例037:排序实例038:矩阵对角线之和实例039:有序列表插入元素实例040:逆序列表实例041:类的方法与变量实例042:变量作用域实例043:作用域、类的方法与变量实例044:矩阵相加实例045:求和实例046:打破循环实例047:函数交换变量实例048:数字比大小实例049:lambda实例050:随机数实例051:按位与实例052:按位或实例053:按位异或实例054:位取反、位移动实例055:按位取反实例056:画圈实例057:画线实例058:画矩形实例059:画图(丑)实例060:字符串长度实例061:杨辉三角实例062:查找字符串实例063:画椭圆实例064:画椭圆、矩形实例065:画组合图形实例066:三数排序实例067:交换位置实例068:旋转数列实例069:报数实例070:字符串长度II实例071:输入和输出实例072:创建链表实例073:反向输出链表实例074:列表排序、连接实例075:不知所云实例076:做函数实例077:遍历列表实例078:字典实例079:字符串排序实例080:猴子分桃实例081:求未知数实例082:八进制转十进制实例083:制作奇数实例084:连接字符串实例085:整除实例086:连接字符串II实例087:访问类成员实例088:打印星号实例089:解码实例090:列表详解实例091:time模块实例092:time模块II实例093:time模块III实例094:time模块IV实例095:转换时间格式实例096:计算复读次数实例097:磁盘写入实例098:磁盘写入II实例099:磁盘读写实例100:列表转字典实例001:数字组合题目有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?程序分析遍历全部可能,把有重复的剃掉。

python基础能力测试习题(带答案详解)

python基础能力测试习题(带答案详解)

Python 能力测试题一、选择题1.运行下列程序后,输入了一个数字“100”,并按下Enter 键。

下列说法正确的是( ) 1.a = input("请输入任意内容:") 2.if a == '100':3. print ("你输入的是",a)A 、程序不能运行,出现错误提示信息B 、程序能够运行,没有任何错误信息C 、程序不能运行,出现乱码信息D 、程序能够运行,输出“你输入的是:100”2.下述while 循环体执行的次为( )1.k = 100 2.while k > 1: 3.k= k // 3 A 、6 B 、5 C 、4 D 、33.运行下列程序后,程序输出的结果是( ) 1.sum = 0 2.n = 3 3.for i in range(2, 4): 4.n *= 2 5.sum += n 6.print (sum) A 、9 B 、18 C 、21 D 、364.初始时列表L=[10,13,15,12,14,11],列表中的元素经过一系列位置交换后,最大的元素移动到了列表尾部,位置交换后L=[10,13,12,14,11,15],下述能实现这个功能的代码是( )。

5 5、若元组 y=(‘A ’,‘B ’, ‘C ’, ‘D ’),则能够返回元素‘D ’的语句是( )。

A 、y[0]B 、y[3]C 、y[-2]D 、y[4]6、以下程序的最终打印结果( )。

l = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9 ]print ( l [1 : 4] )A 、[1,2,3]B 、[1,2,3,4]C 、[2,3,4]D 、[2,3]A 、for i in range(6):if L[i] < L[i -1]:L[i],L[i -1] = L[i -1],L[i]B 、for i in range(5): if L[i] < L[i -1]: L[i],L[i -1] = L[i -1],L[i]C 、for i in range(6):if L[i] > L[i+1]:L[i],L[i+1] = L[i+1],L[i] D 、for i in range(5): if L[i] > L[i -1]: L[i],L[i+1] = L[i+1],L[i]7、初始时x = 3,x // 2+x**2 运算后的值为()A、7.5B、10C、8D、10.58、下面程序的作用是()。

大学python基础试题及答案

大学python基础试题及答案

大学python基础试题及答案一、选择题(每题2分,共20分)1. 在Python中,以下哪个关键字用于定义一个函数?A. defB. classC. returnD. import答案:A2. 下列哪个选项是Python中的注释方式?A. // 这是注释B. # 这是注释C. /* 这是注释 */D. -- 这是注释答案:B3. 以下哪个选项是Python中的列表推导式?A. [x for x in range(10)]B. {x for x in range(10)}C. (x for x in range(10))D. [x: x in range(10)]答案:A4. Python中,以下哪个选项是正确的字典定义方式?A. dict = {1: 'apple', 2: 'banana'}B. dict = [1: 'apple', 2: 'banana']C. dict = (1: 'apple', 2: 'banana')D. dict = {'1': 'apple', '2': 'banana'}答案:A5. 在Python中,以下哪个选项是正确的字符串格式化方式?A. "Hello %s" % "world"B. "Hello {}".format("world")C. "Hello {0}".format("world")D. "Hello %d" % "world"答案:C二、填空题(每题2分,共20分)1. Python中的整数类型是________。

答案:int2. 在Python中,以下代码的输出结果是________。

python基础练习题

python基础练习题

Python基础练习题一、变量与数据类型1. 将字符串 "Hello, World!" 赋值给一个变量,并打印该变量。

2. 定义一个整型变量和一个浮点型变量,分别计算它们的和、差、乘积和商。

4. 编写代码,实现整型、浮点型、字符串型之间的类型转换。

二、运算符与表达式1. 计算 9 + 6 3 2 的结果。

3. 编写一个表达式,判断一个数是否既是偶数又是3的倍数。

4. 使用除法运算符,计算 15 除以 2 的结果,并解释为何得到这样的结果。

5. 编写一个表达式,计算两个数的平均值。

三、流程控制1. 编写一个if语句,判断一个数是否大于10,如果是,则打印“该数大于10”。

2. 编写一个for循环,打印1到10的所有偶数。

3. 使用while循环,计算1+2+3++100的和。

5. 编写一个函数,判断一个年份是否为闰年。

四、列表与元组1. 创建一个包含1到10的列表。

2. 将列表中的每个元素乘以2,并打印结果。

3. 编写代码,实现列表的排序和反转。

4. 使用切片操作,获取列表中的第3到第6个元素。

5. 编写一个函数,计算列表中所有偶数的和。

五、字典与集合1. 创建一个包含三个键值对的字典,分别表示姓名、年龄和性别。

2. 通过键访问字典中的值,并修改其中一个键的值。

3. 编写代码,遍历字典中的所有键和值。

4. 创建一个集合,包含1到10的数字,并去除重复元素。

5. 编写一个函数,判断两个集合是否为子集关系。

六、函数与模块1. 编写一个函数,计算两个数的最大公约数。

2. 定义一个斐波那契数列的函数,并打印前10个数字。

3. 导入math模块,计算并打印圆周率的值。

4. 编写一个装饰器,用于计算函数运行时间。

5. 创建一个模块,实现一个简单的计算器功能(加、减、乘、除)。

七、文件操作1. 编写代码,读取一个文本文件的内容,并打印出来。

2. 将一段文字写入一个文本文件,并实现换行。

3. 编写代码,复制一个文件到另一个目录。

Python初学者15道必练题及参考答案

Python初学者15道必练题及参考答案

Python初学者15道必练题
典型、快捷、有效的练习题
可新科技 | Python培训 | 2021
1: 已知两个整数,编写一段函数,返回它们的乘积,如果结果大于1000,则返回两个数的和。

已知:
2 已知0到9共十个数,编写一个从0开始到9结束的循环,在每一步打印当前数与上一个数的和。

预期返回结果:
5: 已知一个数列,如果数列的首尾数字相同,则返回真。

预期返回结果
6: 已知一个数列,编写一个循环,只打印可以被五整除的数。

预期输出结果:
7: 编写一段函数,返回“Emma”这个单词在一个句子中的出现次数。

输入的句子是“Emma is good developer. Emma is a writer”
期望输出结果为:
参考答案2: 不使用任何字符串函数
8: 编写函数,打印如下的数字组合。

9: 前后颠倒一个已知数,如果其结果与原来的数相同,则返回“此数为回文数”,否则返回“不是回文数”。

期望输出结果:
10: 输入两个数列,编写一个函数,将其合成一个数列,条件是:新数列只收录第一数列里的奇数,及第二个数列里的偶数,返回新的数列。

期望输出的结果:
11: 编写一段代码,从一个整数中间反序提取每一个数字。

期望输出结果:
比如, 如果一个整数是7536, 输出结果应该是“6 3 5 7“,数字之间用空格分开。

参考答案:
12: 已知输入的薪水,根据如下的阶梯所得税规定,计算个人所得税。

13: 打印1到10的乘法口诀表期望输出结果:
参考答案:
14: 打印由“*“字符组成的半个倒金字塔图案。

参考答案:。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Advanced computation linguistics1. Collect the most frequent words in 5 genres of Brown Corpus:news, adventure, hobbies, science_fiction, romanceTo collect most frequent words from the given genres we can follow the following steps:>>> import nltk>>> from nltk.corpus import brown>>> brown.categories()['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies','humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance', 'science_fiction']>>> news_text = brown.words(categories=['news','adventure','hobbies','science_fiction','romance'])>>> from nltk.probability import FreqDist>>> fdist=FreqDist([w.lower() for w in news_text])>>> voca=fdist.keys()>>> voca[:50]['the', ',', '.', 'and', 'of', 'to', 'a', 'in', 'he', "''", '``', 'was', 'for','that', 'it', 'his', 'on', 'with', 'i', 'is', 'at', 'had', '?', 'as', 'be', 'you', ';', 'her', 'but', 'she', 'this', 'from', 'by', '--', 'have', 'they', 'said','not', 'are', 'him', 'or', 'an', 'one', 'all', 'were', 'would', 'there', '!', 'out', 'will']>>> voca1=fdist.items()>>> voca1[:50][('the', 18635), (',', 17215), ('.', 16062), ('and', 8269), ('of', 8131), ('to',7125), ('a', 7039), ('in', 5549), ('he', 3380), ("''", 3237), ('``', 3237), ('was', 3100), ('for', 2725), ('that', 2631), ('it', 2595), ('his', 2237), ('on', 2162), ('with', 2157), ('i', 2034), ('is', 2014), ('at', 1817), ('had', 1797), ('?', 1776), ('as', 1725), ('be', 1610), ('you', 1600), (';', 1394), ('her', 1368), ('but', 1296), ('she', 1270), ('this', 1248), ('from', 1174), ('by', 1157), ('--', 1151), ('have', 1099), ('they', 1093), ('said', 1081), ('not', 1051), ('are', 1019), ('him', 955), ('or', 950), ('an', 911), ('one', 903), ('all', 894), ('were', 882), ('would', 850), ('there', 807), ('!', 802), ('out', 781), ('will',775)]This means that the frequency of word “the” is more than others.2. Exclude or filter out all words that have a frequency lower than 15 occurrencies. (hint using conditional frequency distribution)By adding functionalities on the first task of collecting words based on their frequency ofoccurrences, we can filter words which has frequency occurrence of >=15.>>> filteredText= filter(lambda word: fdist[word]>=15,fdist.keys())>>> voca=fdist.keys()>>> filteredText[:50] /*first 50 words*/['the', ',', '.', 'and', 'of', 'to', 'a', 'in', 'he', "''", '``', 'was', 'for','that', 'it', 'his', 'on', 'with', 'i', 'is', 'at', 'had', '?', 'as', 'be', 'you', ';', 'her', 'but', 'she', 'this', 'from', 'by', '--', 'have', 'they', 'said','not', 'are', 'him', 'or', 'an', 'one', 'all', 'were', 'would', 'there', '!', 'out', 'will']>>> filteredText[-50:] /*last 50 words*/['musical', 'naked', 'names', 'oct.', 'offers', 'orders', 'organizations', 'parade', 'permit', 'pittsburgh', 'prison', 'professor', 'properly', 'regarded', 'release', 'republicans', 'responsible', 'retirement', 'sake', 'secrets', 'senior','sharply', 'shipping', 'sir', 'sister', 'sit', 'sought', 'stairs', 'starts', 'style', 'surely', 'symphony', 'tappet', "they'd", 'tied', 'tommy', 'tournament', 'understanding', 'urged', 'vice', 'views', 'village', 'vital', 'waddell', 'wagner', 'walter', 'waste', "we'd", 'wearing', 'winning']3. Then exclude or filter out all stopwords from the lists you have created.(hint using conditional frequency distribution)To filter the stop words we have to define tiny function using the word net library for 'english' language.>>> from nltk.corpus import stopwords>>> stopwords.words('english')['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself', 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those', 'am','is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no','nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', 'should', 'now']>>> def content_fraction(text):... stopwords= nltk.corpus.stopwords.words('english')... content = [w for w in text if w.lower() not in stopwords]... return len(content) / len(text)...>>> content_fraction(nltk.corpus.reuters.words())0.65997695393285261>>> filterdText = filterStopword(freqDist)>>> filterdText[:50][',', '.', "''", '``', '?', ';', '--', 'said', 'would', 'one', '!', 'could', '(', ')', ':', 'time', 'like', ' back','two', 'first', 'man','made', 'Mrs.', 'new', 'get', 'way', 'last', 'long', 'much', 'even', 'years', 'good', 'little', 'also', 'Mr.', 'see','right', 'make', 'got', 'home', 'many', 'never', 'work', 'know','day' , 'around', 'year', 'may', 'came', 'still']>>> freqDist[:50][',', 'the', '.', 'of', 'and', 'to', 'a', 'in', "''", '``', 'was', 'for', 'that', 'he', 'on', 'with', 'his', 'I', 'it','is', 'The', 'had', '?','at', 'as', 'be', ';', 'you', 'her', 'He', '--', 'from', 'by', 'said', 'h ave', 'not','are', 'this', 'him', 'or', 'were', 'an', 'but','would', 'she', 'they', 'one', '!', 'all', 'out ']From the result in filterdText words like 'the', 'it', 'is' and so on does not existcompared to the same number of output with stop words.>>> len(freqDist)2341>>> len(filterdText)2153We can further check that how many stop-words have been removed from the freqDist15 using len( ) function.4. Create a new list of lemmas or roots by normalizing all words by stemmingfor create the normalized list of lemmas we apply the Porter Stemmer nltk functionality.>>> file = open('filterdText.txt')>>> text = file.read()>>> textTokens = nltk.word_tokenize(text)Now we do stemming>>> p = nltk.PorterStemmer ( )>>> rootStemming = [p.stem(t) for t in textTokens]>>> textTokens[:100]['!', '&', "'", "''", "'em", '(', ')', ',', '--', '.', '1', '10', '100', '11', '12', '13', '14', '15', '16', '17', '18', '1958', '1959','1960', '1961', '2', '20', '200', '22', '25', '3', '30', '4', '5', '50', '6', '60 ', '7', '8', '9', ':', ';', '?', 'A.', 'Actually','Af', 'Ah', 'Aj', 'Alexander', 'Also', 'Although', 'Americ a', 'American', 'Americans','Among', 'Angeles','Anne', 'Anniston', 'Another', 'April', 'Association', 'Augu st', 'Austin', 'Avenue', 'B', "B'dikkat", 'B.','Barton', 'Beach', 'Belgians', 'Besides', 'Bill', 'Billy', 'B lue', 'Board', 'Bob','Bobbie', 'Boston', 'Brannon','British', 'C.', 'Cady', 'California', 'Catholic', 'Cath y', 'Center', 'Central', 'Charles', 'Charlie', 'Chicago','Christian', 'Church', 'City', 'Class', 'Clayton', 'Club', 'Co.', 'Coast','Cobb', 'College']This function can display sorted non normalized sample outputs for comparison>>> rootStemming[:100]['!', '&', "'", "''", "'em", '(', ')', ',', '--', '.', '1', '10', '100', '11', '12', '13', '14', '15', '16', '17', '18', '1958', '1959','1960', '1961', '2', '20', '200', '22', '25', '3', '30', '4', '5', '50', '6', '60 ', '7', '8', '9', ':', ';', '?', 'A.','Actual', 'Af','Ah', 'Aj', 'Alexand', 'Also', 'Although', 'America', 'American', 'American', 'Among','Angel', 'Ann','Anniston', 'Anoth', 'April', 'Associ', 'August', 'Austin','Avenu', 'B', "B'dikkat", 'B.','Barton', 'Beach','Belgian', 'Besid', 'Bill', 'Billi', 'Blue', 'Board', 'Bob ', 'Bobbi', 'Boston', 'Brannon','British', 'C.', 'Cadi','California', 'Cathol', 'Cathi','Center','Central','Charl','Charli','Chicago','Christian', 'Church', 'Citi','Class', 'Clayton', 'Club', 'Co.', 'Coast', ' Cobb', 'Colleg']This can sorted stemmed sample output for comparison5. Create a new list of lemmas or roots by normalizing all words by lemmatizationAfter importing the file we need to lemmatize, which is the same step as the previous one:and using the same rawText>>> wnl = nltk.WordNetLemmatizer()>>> rootLemmatize = [wnl.lemmatize(t) for t in textTokens]>>> rootLemmatize[:100] / *the first 100 sorted lemmatized lemmas for comparison*/['!', '&', "'", "''", "'em", '(', ')', ',', '--', '.', '1', '10', '100', '11', '12', '13', '14', '15', '16', '17', '18', '1958', '1959','1960', '1961', '2', '20', '200', '22', '25', '3', '30', '4', '5', '50', '6', '60 ', '7', '8', '9', ':', ';', '?', 'A.', 'Actually','Af', 'Ah', 'Aj', 'Alexander', 'Also', 'Although', 'Americ a', 'American', 'Americans','Among', 'Angeles','Anne', 'Anniston', 'Another', 'April', 'Association', 'Augu st', 'Austin', 'Avenue', 'B', "B'dikkat", 'B.','Barton', 'Beach', 'Belgians', 'Besides', 'Bill', 'Billy', 'B lue', 'Board', 'Bob','Bobbie', 'Boston', 'Brannon','British', 'C.', 'Cady', 'California', 'Catholic', 'Cath y', 'Center', 'Central', 'Charles', 'Charlie', 'Chicago','Christian', 'Church', 'City', 'Class', 'Clayton', 'Club','Co.','Coast','Cobb', 'College']We end this task by writing the out put of the lemmatized lemmas or rootwords to the file '(rootLemmatize.txt').6. Use the most frequent lemmas to find semantic similarities using WordNet.To find synsets with related meanings we have to traverse the WordNet network. knowing which word is semantically related is useful for indexing a collection of texts. For example a search for a general term like 'England' will match for specific terms like 'UK'.Top 100 frequent lemmas:>>> file = open('filterdText.txt') /*from 'filterdText' we get the words*/>>> tmp = file.read()>>> from nltk.tokenize import RegexpTokenizer /*remove punctuations*/>>>>>> tokenizer = RegexpTokenizer(r'\w+')>>> textSimilarity = tokenizer.tokenize(tmp)>>> freqDistSimilarity = FreqDist([w.lower() for w in textSimilarity]) /* extract the first 100 frequent lemmas to new list*/>>> for word in textSimilarity:... freqDistSimilarity.inc(word)>>> tmpFDS = freqDistSimilarity.keys()[:100] /* first 100 most frequent lemmas*/>>> freqDistSimilarity.items()[:50][('s', 64), ('t', 60), ('re', 24), ('d', 22), ('you', 20), ('ll', 18), ('m', 14), ('he', 12), ('let', 12), ('man', 10), ('p',10), ('we', 10), ('I', 8), ('i', 8), ('ve', 8), ('won', 8), ('year', 8), ('B', 6), ('a', 6), ('actually', 6), ('also', 6),('although', 6), ('among', 6), ('another', 6), ('association', 6), ('b', 6), ('beach', 6), ('bill', 6),('blue', 6),('board', 6), ('center', 6), ('central', 6), ('church', 6), (' city', 6), ('class', 6), ('club', 6), ('college', 6), ('come', 6), ('committee',6) ,('council',6),('county',6),('court',6),('day',6),('department',6),('district', 6), ('don', 6), ('earth', 6), ('education', 6), ('even', 6), ('every', 6)]>>> def pathSimilarity(word1,word2, s=wnet.path_similarity): /*path similarity between two words*/... synSets1= wnet.synsets(word1)... synSets2= wnet.synsets(word2)... pointSimilarity = []... for synSet1 in synSets1:... for synSet2 in synSets2:... pointSimilarity.append(s(synSet1,synSet2))... if len(pointSimilarity)==0:... return 0... else:... return max(pointSimilarity)>>> tmpFDS[30:35] /*arbitrary path similarity test for 5 lemmas*/['center', 'central', 'church', 'city', 'class']>>> for word1 in tmpFDS[30:35]:... for word2 in tmpFDS[30:35]:... print word1+' == '+word2+' -->', pathSimilarity(word1,word2)center == center --> 1.0center == central --> 0.25center == church --> 0.25center == city --> 0.166center == class --> 0.5central == center --> 0.2central == central --> 1.0central == church --> 0.083central == city --> 0.111central == class --> 0.083church == center --> 0.25church == central --> 0.2church == church --> 1.0church == city --> 0.166church == class --> 0.2city == center --> 0.166city == central --> 0.111city == church --> 0.166city == city --> 1.0city == class --> 0.25class == center --> 0.5class == central --> 0.166class == church --> 0.2class == city --> 0.25class == class --> 1.0Because of the different sizes of synset for the lemmas we can get different path similarity . An independent path similarity test on the synonym sets also proves the same hypothesis.We continue the analysis with the rest of the lemmas by calling the pathSimilarity( ) function with the provided arguments. From above results we can say that the root word 'class' and'center' has a better semantic similarity.。

相关文档
最新文档