python学习之文件读写统计

把字符串写入文本

file_handle = open('a.txt', mode='w')
file_handle.writelines("You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured \n"
                       "to communicate with your cluster. If you do not already have a cluster, you can create one \n"
                       "by using minikube or you can use one of these Kubernetes playgrounds \n")
file_handle.writelines("The preferred way to create a replicated application is to use a Deployment, which in turn \n"
                       "uses a ReplicaSet. Before the Deployment and ReplicaSet were added to Kubernetes, replicated \n"
                       "applications were configured using a ReplicationController \n")
file_handle.close()

统计文本中每个单词出现的频率并随机输出6个单词

import random

file_handle = open("a.txt", mode="r")
lines = file_handle.readlines()
file_handle.close()
dict = {}
set = set()
for line in lines:
    words = line.split(" ")
    for word in words:
        if word in dict.keys():
            dict[word] += 1
        else:
            dict[word] = 1
            set.add(word)
print(dict)
print(random.sample(list(set), 6))

读出文件内容修改后再写回去

lines = read_handle.readlines()
read_handle.close()
for line in lines:
    line = line.replace("<font face=\"宋体\"><font size=\"5\">", " ")
    line = line.replace("</font></font>", " ")

# 打开方式分为r、w、a三种方式 ,【+】表示可以同时读写,这里没有使用同时读写,写的open必须放在读关闭之后不然会变成空文件
write_handle = open("a.txt", mode="w")
write_handle.writelines(lines)
write_handle.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值