练习题3
1.统计文件数据中字母e出现的次数(不不区分大小写)
文件内容:hello friend, can you speak English!
结果:4
分析:将文件内容读出,然后统计读出的字符串串中字符e的个数(字符串串count功能)
with open('1.txt', 'r', encoding='utf-8') as f:
res = f.read()
print(type(res),'字符串e的个数为', res.count('e'))
2.统计文件数据中出现的的所有字符与该字符出现的个数(不区分大小写,标点与空格也算)
文件内容:hello friend, can you speak English!
结果:
{
‘h’: 1,
‘e’: 4,
‘l’: 3,
‘o’: 2,
’ ': 5,
…
}
分析:将文件内容读出,然后统计读出的字符串串中每个字符的个数,形成字段(for遍历读取的字符串串)
res_dic = {}
with open('1.txt', 'r', encoding='utf-8') as f:
char = f.read()
print(char)
for i in char:
i = i.lower()
if i in res_dic:
res_dic[i] += 1
else:
res_dic[i] = 1
print(res_dic)
3.读取文件内容,分析出所有的账号及对应的密码
文件内容:owen:123456|egon:123qwe|liuxx:000000
结果:
{
‘owen’: ‘123456’,
‘egon’: ‘123qwe’,
‘liuxx’: ‘000000’
}
分析:将文件内容读出,然后按|拆分出 账号:密码 格式的子字符串,再按:拆分成 账号及密码,存放到字典中
res_dic = {}
with open('2.txt', 'r', encoding='utf-8') as f:
list1 = f.read().split("|")
for i in list1:
k, v = i.split(":")
res_dic[k] = v
print(res_dic)
4.在题3的基础上,账号密码已经被存储在文件中&#x