該作業要求來于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2646
一、作業要求
1.字元串操作:
- 解析身份證号:生日、性别、出生地等。
- 凱撒密碼編碼與解碼
- 網址觀察與批量生成
2.英文詞頻統計預處理
- 下載下傳一首英文的歌詞或文章或小說,儲存為utf8檔案。
- 從檔案讀出字元串。
- 将所有大寫轉換為小寫
- 将所有其他做分隔符(,.?!)替換為空格
- 分隔出一個一個的單詞
- 并統計單詞出現的次數。
二、字元串操作
1.解析身份證号:生日、性别、出生地等。
代碼如下:
1 class GetInformation(object):
2
3 def __init__(self,id):
4 self.id = id
5 self.birth_year = int(self.id[6:10])
6 self.birth_month = int(self.id[10:12])
7 self.birth_day = int(self.id[12:14])
8
9 def get_birthday(self):
10 """通過身份證号擷取出生日期"""
11 birthday = "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)
12 return birthday
13
14 def get_sex(self):
15 """男生:1 女生:2"""
16 num = int(self.id[16:17])
17 if num % 2 == 0:
18 return 2
19 else:
20 return 1
21
22 def get_age(self):
23 """通過身份證号擷取年齡"""
24 now = (datetime.datetime.now() + datetime.timedelta(days=1))
25 year = now.year
26 month = now.month
27 day = now.day
28
29 if year == self.birth_year:
30 return 0
31 else:
32 if self.birth_month > month or (self.birth_month == month and self.birth_day > day):
33 return year - self.birth_year - 1
34 else:
35 return year - self.birth_year
36
37 id = '440823199807195613'
38 birthday = GetInformation(id).get_birthday() # 1998-07-19
39 age = GetInformation(id).get_age() # 2
2.凱撒密碼編碼與解碼
代碼如下:
1 def encryption():
2 str_raw = input("請輸入明文:")
3 k = int(input("請輸入位移值:"))
4 str_change = str_raw.lower()
5 str_list = list(str_change)
6 str_list_encry = str_list
7 i = 0
8 while i < len(str_list):
9 if ord(str_list[i]) < 123-k:
10 str_list_encry[i] = chr(ord(str_list[i]) + k)
11 else:
12 str_list_encry[i] = chr(ord(str_list[i]) + k - 26)
13 i = i+1
14 print ("加密結果為:"+"".join(str_list_encry))
15 def decryption():
16 str_raw = input("請輸入密文:")
17 k = int(input("請輸入位移值:"))
18 str_change = str_raw.lower()
19 str_list = list(str_change)
20 str_list_decry = str_list
21 i = 0
22 while i < len(str_list):
23 if ord(str_list[i]) >= 97+k: str_list_decry[i] = chr(ord(str_list[i]) - k)
24 else: str_list_decry[i] = chr(ord(str_list[i]) + 26 - k)
25 i = i+1
26 print ("解密結果為:"+"".join(str_list_decry))
27 while True:
28 print (u"1. 加密")
29 print(u"2. 解密")
30 choice = input("請選擇:")
31 if choice == "1": encryption()
32 elif choice == "2": decryption()
33 else: print (u"您的輸入有誤!")
3.網址觀察與批量生成
for i in range(2,6):
url='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
print(url)
二.英文詞頻統計預處理
f = open(r'D:\pyhomework\bigbigword.txt',encoding='utf8')
sep = ',./<>?`-_=+'
text = f.read()
print(text)
f.close()
text = text.lower()
for i in sep:
text = text.replace(i,' ')
print(text.split())
print(text.count('big'),text.count('world'))