0%

python-第七天学习

python3基础学习

hashlib的使用

设计一个验证用户登录的函数,根据用户输入的口令是否正确,返回True 或 False:

1
2
3
4
5
6
7
db = {
'michael': 'e10adc3949ba59abbe56e057f20f883e',
'bob': '878ef96e86145580c38c87f0410ad153',
'alice': '99b1c2188db85afee403b1536010c2c9'
}
def login(user, password):
pass

so easy,直接贴代码吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python
# coding=utf-8
import hashlib

def calc_md5(passwd):
md5 = hashlib.md5()
md5.update(passwd.encode('utf-8'))
return md5.hexdigest()

db = {
'michael': 'e10adc3949ba59abbe56e057f20f883e',

'bob': '878ef96e86145580c38c87f0410ad153',

'alice': '99b1c2188db85afee403b1536010c2c9'
}

def login(user,password):
print (db[user],calc_md5(password))
if db[user] == calc_md5(password):
return True
else:
return False

if login('bob','123456'):
print ("success")
else:
print ("fail")

根据用户输入的登录名和口令模拟用户注册,计算更安全的 MD5:

1
2
3
4
5
6
db = {}
def register(username, password):
db[username] = get_md5(password + username + 'the-Salt')
然后,根据修改后的 MD5 算法实现用户登录的验证:
def login(username, password):
pass

这种题目也是送分题啊,直接贴代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# coding=utf-8
import hashlib
db = {}
def calc_md5(passwd):
md5 = hashlib.md5()
md5.update(passwd.encode('utf-8'))
return md5.hexdigest()

def register(username, password):
db[username] = calc_md5(password + username + 'the-Salt')

def login(username,password):
if db[username] == calc_md5(password + username + 'the-Salt'):
print ("sucess")
else:
print("fail")

register('bob','123456')
register('robot','123456')
login('bob','12345')
login('bob','123456')

xml解析

请利用 SAX 编写程序解析 Yahoo 的 XML 格式的天气预报,获取当天
和第二天的天气:

这部分对我来说有点难理解,不过查阅资料和看博客后自己依葫芦画瓢还是做出来了
贴上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
# coding=utf-8
from xml.parsers.expat import ParserCreate
data = r'''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
<title>Yahoo! Weather - Beijing, CN</title>
<lastBuildDate>Wed, 27 May 2015 11:00 am CST</lastBuildDate>
<yweather:location city="Beijing" region="" country="China"/>
<yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
<yweather:wind chill="28" direction="180" speed="14.48" />
<yweather:atmosphere humidity="53" visibility="2.61" pressure="1006.1" rising="0" />
<yweather:astronomy sunrise="4:51 am" sunset="7:32 pm"/>
<item>
<geo:lat>39.91</geo:lat>
<geo:long>116.39</geo:long>
<pubDate>Wed, 27 May 2015 11:00 am CST</pubDate>
<yweather:condition text="Haze" code="21" temp="28" date="Wed, 27 May 2015 11:00 am CST" />
<yweather:forecast day="Wed" date="27 May 2015" low="20" high="33" text="Partly Cloudy" code="30" />
<yweather:forecast day="Thu" date="28 May 2015" low="21" high="34" text="Sunny" code="32" />
<yweather:forecast day="Fri" date="29 May 2015" low="18" high="25" text="AM Showers" code="39" />
<yweather:forecast day="Sat" date="30 May 2015" low="18" high="32" text="Sunny" code="32" />
<yweather:forecast day="Sun" date="31 May 2015" low="20" high="37" text="Sunny" code="32" />
</item>
</channel>
</rss>
'''
weather_dict={}
day = 0
class WeatherSaxHandler(object):
def start_element(self, name, attrs):
global weather_dict,day
if name == 'yweather:location':
weather_dict['city'] = attrs['city']
weather_dict['country'] = attrs['country']
if name == 'yweather:forecast':
day = day + 1
if day == 1 :
weather_dict['today']={'text':attrs['text'], 'low':int(attrs['low']), 'high':int(attrs['high'])}
if day == 2 :
weather_dict['tomorrow']={'text':attrs['text'], 'low':int(attrs['low']), 'high':int(attrs['high'])}
def end_element(self, name):
pass
def char_data(self, text):
pass
def parse_weather(xml):
handler = WeatherSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.CharacterDataHandler = handler.char_data
parser.EndElementHandler = handler.end_element
parser.Parse(xml)
return weather_dict

weather = parse_weather(data)

assert weather['city'] == 'Beijing', weather['city']

assert weather['country'] == 'China', weather['country']

assert weather['today']['text'] == 'Partly Cloudy',weather['today']['text']

assert weather['today']['low'] == 20, weather['today']['low']

assert weather['today']['high'] == 33, weather['today']['high']

assert weather['tomorrow']['text'] == 'Sunny',weather['tomorrow']['text']

assert weather['tomorrow']['low'] == 21, weather['tomorrow']['low']

assert weather['tomorrow']['high'] == 34, weather['tomorrow']['high']

print('Weather:', str(weather))

html解析

找一个网页,例如 https://www.python.org/events/python-events/,用浏览器查看源码并复制,然后尝试解析一下 HTML,输出 Python 官网发布的会议时间、名称和地点

  • 代码抄别人的,不过懂了,自己打了一遍
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    #!/usr/bin/env python
    # coding=utf-8
    from html.parser import HTMLParser
    from html.entities import name2codepoint
    import re
    class MyHTMLParser(HTMLParser):
    def __init__(self):
    HTMLParser.__init__(self)
    self.is_time = False
    self.is_title = False
    self.is_year = False
    self.is_location = False
    self.info = []
    def handle_starttag(self, tag, attrs):
    if tag == 'time':
    self.is_time = True
    if tag == 'h3' and ('class', 'event-title') in attrs:
    self.is_title = True
    if tag == 'span' and ('class', 'event-location') in attrs:
    self.is_location = True
    if tag == 'span' and ('class', 'say-no-more') in attrs:
    self.is_year = True
    def handle_data(self,data):
    if self.is_time:
    self.is_time = False
    mydict = {'time':data}
    self.info.append(mydict)
    if self.is_title:
    self.is_title = False
    mydict = {'title':data}
    self.info.append(mydict)
    if self.is_location:
    self.is_location = False
    mydict = {'location':data}
    self.info.append(mydict)
    if self.is_year:
    self.is_year = False
    mydict = {'date':data}
    if re.match(r'[0-9]',data.strip()):
    self.info.append(mydict)

    def getinfo(data):
    parser = MyHTMLParser()
    parser.feed(data)
    count = 0
    for x in parser.info:
    for key in x:
    print(key + ':' + str(x[key]))
    count = count + 1
    if count % 4 == 0:
    print ('--------------------------------')
    with open('1.html', 'r') as f:
    htmlcont = f.read()
    getinfo(htmlcont)

本文作者:NoOne
本文地址https://noonegroup.xyz/posts/b164eb0e/
版权声明:转载请注明出处!