1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
li = [] with open('a.txt', encoding='utf-8', mode='r') as f1: for i in f1: l2 = i.strip().split() dic = {'name':l2[0], 'price':l2[1], 'amount':l2[2]} li.append(dic) print(li) sum = 0 for j in li: sum = sum + int(j['price']) * int(j['amount']) print(sum) 优化拓展 name_list = ['name', 'price', 'amount'] li = [] with open('a.txt', encoding='utf-8', mode='r') as f1: for i in f1: l2 = i.strip().split() # dic = {} # for j in range(len(l2)): # dic[name_list[j]] = l2[j] dic = dict(zip(name_list, l2)) # 前面三句可以优化成这一句,易读性也更强 li.append(dic) print(li) sum = 0 for k in li: sum = sum + int(k['price']) * int(k['amount']) print(sum)
2,有如下文件:
-------
alex是老男孩python发起人,创建人。
alex其实是人妖。
谁说alex是sb?
你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
----------
将文件中所有的alex都替换成大写的SB。
import os with open('alex.txt', encoding='utf-8', mode='r') as f1, open('SB.txt', encoding='utf-8', mode='w') as f2: for i in f1: print(i) new_i = i.replace('alex', 'SB') f2.write(new_i) os.remove('alex.txt') os.rename('SB.txt', 'alex.txt')
3. 文件a1.txt内容:每一行内容分别为商品名字,价钱,个数。
文件内容:
name:apple price:10 amount:3 year:2012
name:tesla price:100000 amount:1 year:2013
通过代码,将其构建成这种数据类型:
[{'name':'apple','price':10,'amount':3},
{'name':'tesla','price':1000000,'amount':1}......]
并计算出总价钱。
lis = [] dic = {} with open('a1.txt', encoding='utf-8', mode='r') as f2: for i in f2: li = i.strip().split() for j in li: KeyVal = j.split(':') dic.setdefault(KeyVal[0], KeyVal[1]) lis.append(dic) dic = {} print(lis) sum = 0 for k in lis: sum =sum + int(k['amount'])*int(k['price']) print(sum)
lis = [] dic = {} with open('a1.txt', encoding='utf-8', mode='r') as f2: for i in f2: li = i.strip().split() for j in li: KeyVal = j.split(':') dic.setdefault(KeyVal[0], KeyVal[1]) lis.append(dic) dic = {} print(lis)
4,文件a2.txt内容:每一行内容分别为商品名字,价钱,个数。
文件内容:
序号 部门 人数 平均年龄 备注
1 python 30
26 单身狗
2 Linux 26
30 没对象
3 运营部 20
24 女生多
通过代码,将其构建成这种数据类型:
[{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'单身狗'},
......]
li = [] with open('a2.txt',encoding='utf-8')as f1: key = f1.readline().strip().split() for i in f1: val = i.strip().split() dic = dict(zip(key,val)) li.append(dic) print(li)