字符串、文件操作,英文词频统计预处理
1.字符串操作:
- 解析身份证号:生日、性别、出生地等。
import des as des if __name__ == '__main__': def sex(str1): # 查看性别 if int(str1[-2]) % 2 == 0: return '女' else: return '男' idDes = ['广东省广州市市辖区', '广东省广州市东山区', '广东省广州市荔湾区', '广东省广州市越秀区', '广东省广州市海珠区', '广东省广州市天河区'] idNum = input('输入十八位(广州)身份证号码:') brith = idNum[6:14] # test = idNum[:4] if (idNum[:4] == '4401'): if (idNum[4:6] == '01'): test =idNum[4:6] des = idDes[0] if (idNum[4:6] == '02'): des = idDes[1] if (idNum[4:6] == '03'): des = idDes[2] if (idNum[4:6] == '04'): des = idDes[3] if (idNum[4:6] == '05'): des = idDes[4] if (idNum[4:6] == '06'): des = idDes[5] # elif des == 0: # print('信息未录入') print('身份证归属地:',des) print('生日:',brith) print('性别:',sex(idNum))
- 凯撒密码编码与解码
if __name__ == '__main__':choose = input("请选择: 1.加密 2.解密 :") ch = int(choose) # 加密 def encode(txt, ofs): t = "" for ch in txt: if 'a' <= ch <= 'z': t += chr(ord('a') + ((ord(ch) - ord('a')) + ofs) % 26) elif 'A' <= ch <= 'Z': t += chr(ord('A') + ((ord(ch) - ord('A')) + ofs) % 26) else: t += ch return t # 解密 def decode(txt, ofs): t = "" for ch in txt: if 'a' <= ch <= 'z': t += chr(ord('a') + ((ord(ch) - ord('a')) - ofs) % 26) elif 'A' <= ch <= 'Z': t += chr(ord('A') + ((ord(ch) - ord('A')) - ofs) % 26) else: t += ch return t inputTxt = input("请输入:") ofs = 3 if ch == 1: result = encode(txt=inputTxt, ofs=ofs) print("加密为:" + result) else: result = decode(txt=inputTxt, ofs=ofs) print("解密为:" + result)
- 网址观察与批量生成
if __name__ == '__main__':import webbrowser as web url = "http://news.gzcc.cn/html/xiaoyuanxinwen/2.html" web.open_new_tab(url) for i in range(3, 10): url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' + str(i) + '.html' web.open_new_tab(url) print(url)
2.英文词频统计预处理
- 下载一首英文的歌词或文章或小说,保存为utf8文件。
- 从文件读出字符串。
- 将所有大写转换为小写
- 将所有其他做分隔符(,.?!)替换为空格
- 分隔出一个一个的单词
- 并统计单词出现的次数。
if __name__ == '__main__':fo = open("test.txt", 'r') #读取英文文章 text = fo.read() #大写转小写 text = text.lower() print(text+"\n") strs = {",", '.', "?", "!", ';'} #替换符号为空格 for str in strs: text = text.replace(str, "") #分割单词 text = text.split() print(text) #统计词频 textS = {} for i in text: count = text.count(i) textS[i] = count textS = sorted(textS.items(), key=lambda text:text[1]) print(textS)