30、将一个文件的所有单词倒序写入文件中
#1
import re
with open('e:\\test\\5.txt',encoding='utf-8')as fp:
content=fp.read()
words=re.findall(r'\b[a-z]+\b',content)
with open('e:\\aa.txt','w',encoding='utf-8')as fp:
fp.write(''.join(words[::-1]))
#2
#读取文件的内容存到content中
with open('e:\\test\\5.txt',encoding='utf-8')as fp:
content=fp.readlines()
print(content)
#切掉逗号添加到临时列表temp中
temp=[]
for line in content:
for word in line.split(','):
temp.append(word)
#切空白,把单词添加到result中
result=[]
for words in temp:
for word in words.split():
result.append(word)
#打开一个文件,把result列表中的内容写入到文件中
with open('e:\\aa.txt','w',encoding='utf-8')as fp:
fp.write(''.join(result[::-1]))
习题1:有四个数字:1,2,3,4 ,能组成多少个互不相同且无重复数字的三位数
result=[]
for i in '1234':
for j in '1234':
for k in '1234':
if i!=j and i!=k and j!=k:
result.append(i+k+j)
print(len(result))
习题2:判断 一个文件中有几行含英文单词
with open('e:\\test\\5.txt','r',encoding='utf-8')as fp:
content=fp.readlines()
line_count=0
for line in content:
for word in line:
if (word >='a' and word<='z') or (word >='A' and word <='Z'):
line_count+=1
break
print(line_count)
习题3:以r+方式,把一句话追加到文件末尾,然后读出所有文件
with open('e:\\test\\5.txt','r+',encoding='utf-8')as fp:
fp.seek(0,2)#把游标定位到末尾
fp.write('baosheng')
fp.seek(0,0)
content=fp.read()
print(content)
习题4:把一个文件内容中的boy替换成xxx
with open('e:\\test\\5.txt','r',encoding='utf-8')as fp:
content=fp.readlines()
with open('e:\\test\\aa.txt','w',encoding='utf-8')as fp:
for line in content:
fp.write(line.replace('boy','xxx'))
#2
with open('e:\\test\\5.txt','r+',encoding='utf-8')as fp:
content=fp.read()
content=content.replace('boy','xxx')
fp.seek(0,0)
fp.write(content)
#3
with open('e:\\test\\5.txt','r+',encoding='utf-8')as fp:
content=fp.readlines()
fp.seek(0,0)
for line in content:
fp.write(line.replace('boy','xxx'))
python练习2020/7/27
最新推荐文章于 2024-09-14 19:55:48 发布
这篇博客主要介绍了作者在2020年7月27日进行的Python编程练习,涵盖了相关技术点和经验分享。
摘要由CSDN通过智能技术生成