python练习2020/7/27

这篇博客主要介绍了作者在2020年7月27日进行的Python编程练习,涵盖了相关技术点和经验分享。
摘要由CSDN通过智能技术生成
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'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值