第九节-更具有Python风格地编程

命名3:
类:首字母大写,不用下划线分割单词
变量:小写字母,用下划线分割单词


数据处理的花招
"""
==================================
数据处理的花招
==================================
"""
#1、
man = ("tht","tao",185,"[email protected]")
first_name, last_name, height, email1 = man
_, _, _, email2 = man
print(first_name, last_name, height, email1,email2)

#2、交换两个值
a = 1
b = 2
a,b = b,a
print(a,b)

#3、组合字符串
colors = ['we','are','family','!']
print(' '.join(colors))

#4、循环
colors = ['red','yellow','green','blue']
for color in colors:
    print(color)

#5、带下标循环
colors = ['red','yellow','green','blue']
for idx,color in enumerate(colors):
    print(idx,"-->",color)

#6、all和any
ages = [18,19,20,21,22,23,24]
if all(map(lambda x:x >= 18,ages)):
    print('All are adults')
if any(map(lambda x:x == 18,ages)):
    print('Found 18-year-old')
>>
2 1
we are family !
red
yellow
green
blue
0 --> red
1 --> yellow
2 --> green
3 --> blue
All are adults
Found 18-year-old
习题1
使用 try-except 处理文件不存在时的读取任务. 当文件不存在时, 打印错误信息
======================================
习题1
使用 try-except 处理文件不存在时的读取任务
======================================
"""
import os
try:
    f = open("E:/test/class.txt",'r',encoding="utf-8")
    f.write("这是一个测试文件,用于测试异常")
    f.close()
except IOError as error:
    print(error)
collors = [1,2,3,4]
for collor in collors:
    print(collor)
>>
[Errno 2] No such file or directory: 'E:/test/class.txt'
1
2
3
4



习题2
使用 try-except-else-finally 完成下面功能
1. 尝试直接读取某一文件,
2. 当报错为编码不正确时, 使用 chardet.detect 函数检测文件编码,   并使用检测函数所得编码打开文件
3. 在 else 的部分处理数据, 存储到名为 data 的列表中.
4. 最终在 finally 部分打印提示信息 "完成文件读取"
 
data = []
file_dir = "./test_data/test_utf-8_第九节.txt"
try:
    with open(file_dir,"r",encoding="ANSI") as file_in:
        data = file_in.readlines()
except UnicodeDecodeError as error:
    print(error)
    #修复编码问题
    from chardet import detect
    file = open(file_dir,"rb")
    enc = detect(file.read(1024))['encoding']
    print(enc)
    with open(file_dir, "r", encoding=enc) as file_in:
        data = file_in.readlines()
        #进行文件的操作处理
finally:
    #也可以在这里进行文件的操作处理
    print("done!")
print(data)
>>
'mbcs' codec can't decode byte 0x9f in position 15: No mapping for the Unicode character exists in the target code page.
utf-8
done!
['sdfg sg飞虎队\n', 'dry很多不算法\n', '的不敢当的鬼x\n', '很多不过我豆d']

习题3
使用字典推导式生成一个嵌套的字典
它的内容为
{1:{'A': 'a'},
2:{'B': 'b'},...
26:{'Z': 'z'}}
from pprint import pprint
alphabet = {x:{chr(x+64):chr(x+96)} for x in range(1,27)}
print(alphabet)
pprint(alphabet)
>>
{1: {'A': 'a'}, 2: {'B': 'b'}, 3: {'C': 'c'}, 4: {'D': 'd'}, 5: {'E': 'e'}, 6: {'F': 'f'}, 7: {'G': 'g'}, 8: {'H': 'h'}, 9: {'I': 'i'}, 10: {'J': 'j'}, 11: {'K': 'k'}, 12: {'L': 'l'}, 13: {'M': 'm'}, 14: {'N': 'n'}, 15: {'O': 'o'}, 16: {'P': 'p'}, 17: {'Q': 'q'}, 18: {'R': 'r'}, 19: {'S': 's'}, 20: {'T': 't'}, 21: {'U': 'u'}, 22: {'V': 'v'}, 23: {'W': 'w'}, 24: {'X': 'x'}, 25: {'Y': 'y'}, 26: {'Z': 'z'}}
{1: {'A': 'a'},
2: {'B': 'b'},
3: {'C': 'c'},
4: {'D': 'd'},
5: {'E': 'e'},
6: {'F': 'f'},
7: {'G': 'g'},
8: {'H': 'h'},
9: {'I': 'i'},
10: {'J': 'j'},
11: {'K': 'k'},
12: {'L': 'l'},
13: {'M': 'm'},
14: {'N': 'n'},
15: {'O': 'o'},
16: {'P': 'p'},
17: {'Q': 'q'},
18: {'R': 'r'},
19: {'S': 's'},
20: {'T': 't'},
21: {'U': 'u'},
22: {'V': 'v'},
23: {'W': 'w'},
24: {'X': 'x'},
25: {'Y': 'y'},
26: {'Z': 'z'}}

猜你喜欢

转载自blog.csdn.net/sdhotn/article/details/80323533
今日推荐