A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 肖慎江 初级黑马   /  2018-8-1 23:27  /  785 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1.找出具体的单词
text='I can really miss you, you know?' #定义一个语句
print len(text) #输出句子长度,包括空格
text1=text.split(' ') #以空格拆分语句
print text1
print [w for w in text1 if len(w)>3] #找出text1中长度大于三的单词
print [w for w in text1 if w.endswith('s')] #找出在text1中以s结尾的单词

2.用set()找出独特的单词
text2='To be or not to be'
text3=text2.split(' ')
print len(text3) # 6
print set(text3) # 这里会发现To和to会被认为是不同的单词
print len(set(text3)) #会输出5,(希望是4)
print set([w.lower() for w in text3])  #只需要将所有单词先变小写,再找出独特词汇

3.用于字符比较的函数
假设s和a均为字符,
a.startswith(s) #是否以s开口
a.endswith(s) #是否以s结尾
a.isalpha() ; a.isdigit(); a.isalnum()  #alpha代表字母,digit代表0-9的数字,alnum代表字母或数字
a.isupper(); a.islower(); a.istitle() #当全部字母为大写时,isupper为true,istitle只当首字母大写才为true
4.字符的操作
假设a为语句
a.lower(); a.upper(); a.title(); a.split() #分别用于转换大小写和拆分字符
a.split(); a.splitlines(); a.rsplit()  #可以用于不同目的拆分,split默认从左到右,split(' ',1)指定了最大拆分数目,rsplit从右边开始拆分
[w for w in a.split() if w.startswith('#')] #找到句子a中以#字符开头的单词
a.join(s) #在s中循环插入a
s.strip() ; s.rstrip() # 将空格和tab都分离出来,rstrip表示从右往左
s.find(t)
list(text) # 将一段文字或者单词拆分为字符 等同于 [w for w in text]
a.split() 后如果出现很多空格和tab,那么可以通过a.strip().split()来清洗数据
a.find(); a.rfind(); a.replace('o','O') #替换和查找
f=open('xxx.txt','r')
f.readline() # read file line by line
f.read() # read lines of the full files
f.read().splitlines()  # read characters into lines

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马