# 2.统计⽂文件数据中出现的的所有字符与该字符出现的个数(不不区分⼤大⼩小写,标点与空格也算) # ⽂文件内容:hello friend, can you speak English! # 结果: { # 'h': 1, # 'e': 4, # 'l': 3, # 'o': 2, # ' ': 5, # ... # } # 分析:将⽂文件内容读出,然后统计读出的字符串串中每个字符的个数,形成字段(for遍历读取的字符 串串)
dic={} lst=[] with open(r'/Users/zhouyuqiang/Documents/面向对象/day22/周玉强/count.txt', 'r', encoding='utf-8') as f: data=f.readline() print(type(data)) for i in data: lst.append(i) for i in lst: dic[i]=lst.count(i) print(dic) 结果:
/anaconda3/envs/python36-oldboy/bin/python /Users/zhouyuqiang/Documents/面向对象/day22/周玉强/day03-作业.py
<class 'str'>{'h': 2, 'e': 3, 'l': 3, 'o': 2, ' ': 5, 'f': 1, 'r': 1, 'i': 2, 'n': 3, 'd': 1, ',': 1, 'c': 1, 'a': 2, 'y': 1, 'u': 1, 's': 2, 'p': 1, 'k': 1, 'E': 1, 'g': 1, '!': 1, '\n': 1}
方法二:参考:
ss="abcddddf dwdwd fefe$22 222223dsdd .wdd, 2e2e!" lst=[] dic={} for i in ss: lst.append(i) print(lst) for key in lst: dic[key]=lst.count(key) print(dic)
结果: {'a': 1, 'b': 1, 'c': 1, 'd': 12, 'f': 3, ' ': 9, 'w': 3, 'e': 4, '$': 1, '2': 9, '3': 1, 's': 1, '.': 1, ',': 1, '!': 1}