該作業要求來自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2646
1.字元串操作:
解析身份證号:生日、性别、出生地
ID=input('請輸入十八位身份證号碼: ')
if len(ID)==18:
print("你的身份證号碼是 "+ID)
else:
print("錯誤的身份證号碼")
ID_add=ID[0:6]
ID_birth=ID[6:14]
ID_sex=ID[14:17]
ID_check=ID[17]
#ID_add是身份證中的區域代碼,如果有一個行政區劃代碼字典,就可以用擷取大緻位址#
year=ID_birth[0:4]
moon=ID_birth[4:6]
day=ID_birth[6:8]
print("生日: "+year+'年'+moon+'月'+day+'日')
if int(ID_sex)%2==0:
print('性别:女')
else:
print('性别:男')
#此部分應為錯誤判斷,如果錯誤就不應有上面的輸出,如何實作?#
W=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
ID_num=[18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2]
ID_CHECK=['1','0','X','9','8','7','6','5','4','3','2']
ID_aXw=0
for i in range(len(W)):
ID_aXw=ID_aXw+int(ID[i])*W[i]
ID_Check=ID_aXw%11
if ID_check==ID_CHECK[ID_Check]:
print('正确的身份證号碼')
else:
print('錯誤的身份證号碼')
運作效果

凱撒密碼編碼與解碼
在密碼學中,我們把想要加密的消息叫做明文(plain text)。把明文轉換成加密後的消息叫做對明文加密(encrypting),明文加密後變成(cipher text)。
凱撒密碼的密鑰是1到26之間的一個數字。除非知道這個鍵(即用于加密消息的數字),否則無法對這個保密的代碼進行解密。凱撒密碼是人類最早發明的密碼之一,原理是擷取消息中的每個字母,并用一個“移位後的”字母來代替它,如果把字母A移動1格,就會得到字母B,移動兩格,就會得到字母C。
MAX_KEY_SIZE = 26
def getMode():
while True:
print('請選擇加密或解密模式,或者選擇暴力破解:')
print('加密:encrypt(e)')
print('解密:decrypt(d)')
print('暴力破解:brute(b)')
mode = input().lower()
if mode in 'encrypt e decrypt d brute b'.split():
return mode
else:
print('請輸入"encrypt"或"e"或"decrypt"或"d"或"brute"或"b"!')
def getMessage():
print('請輸入你的資訊:')
return input()
def getKey():
key = 0
while True:
print('請輸入密鑰數字(1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >=1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
if mode[0] != 'b':
key = getKey()
print('你要翻譯的資訊是:')
if mode[0] != 'b':
print(getTranslatedMessage(mode, message, key))
else:
for key in range(1, MAX_KEY_SIZE + 1):
print(key, getTranslatedMessage('decrypt', message, key))
運作效果:
網址觀察與批量生成
print(r"搜尋結果如下");
url="https://list.jd.com/list.html?tid=1006238"
s="&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s="
print("第1頁網址為{}".format(url));
for i in range(5):
arg=url+s+str(i*44);
print("第{}頁網址為{}".format(i+2,url));
2.英文詞頻統計預處理
- 下載下傳一首英文的歌詞或文章或小說,儲存為utf8檔案。
- 從檔案讀出字元串。
- 将所有大寫轉換為小寫
- 将所有其他做分隔符(,.?!)替換為空格
- 分隔出一個一個的單詞
- 并統計單詞出現的次數。
fo = open(r'D:\PycharmProjects\test1\music.txt', encoding='utf-8')
text = fo.read()
fo.close()
text = text.lower() # 轉換成小寫
sep = ",.?!:''\n'"
result = {}
for s in sep: # 去除各種符号,用空格代替
text = text.replace(s, ' ')
a = text.split(' ') # 分隔出單詞
print("單詞 個數")
for w in a:
if w != '':
print("{:<10} {:<5}".format(w, text.count(w))) # 格式化輸出
運作結果: