字符串操作、文件操作,英文词频统计预处理

一.字符串操作

1、解析身份证号:生日、性别、出生地等。

代码如下:

province={'北京':11,'天津':12,'上海':31,'重庆':50,
'河北':13,'河南':41,'云南':53,'辽宁':21,'黑龙江':23,
'湖南':43,'安徽':34,'山东':37,'新疆':65,'江苏':32,'浙江':33,
'江西':36,'湖北':42,'广西':45,'甘肃':62,'山西':14,
'内蒙古':15,'陕西':61,'吉林':22,'福建':35,'贵州':52,'广东':44,
'青海':63,'西藏': 54,'四川':51,'宁夏':64,'海南':46}
identification=input('请输入您的身份证号码:')
if int(identification[-2])%2==0:
print('性别:'+'女')
else:
print('性别:' + '男')
for i in province:
if int(province[i])==int(identification[0:2]):
print(i+'人')
break
print('出生日期:'+identification[6:10]+'年'+
identification[10:12]+'月'
+identification[12:14]+'日')



运行结果:

2、凯撒密码编码与解码

代码如下:

 # 加密函数

def encrypt(text):
str=''
for i in text:
str=str+chr(ord(i)+3)
return str

# 解密函数
def decrypt(text):
str=""
for i in text:
str = str + chr(ord(i) - 3)
return str
print('1:解码 2:加密')
while True:
choice=int(input('请选择1或2:'))
if choice in [1,2]:
break
if choice==1:
text=input('请输入需要解密的文字:')
print(decrypt(text))
else:
text = input('请输入需要加密的文字:')
print(encrypt(text))




运行结果:

 

 

3、网址观察与批量生成

 代码如下:

import webbrowser
for i in range(2,5):
webbrowser.open_new('http://news.gzcc.cn/html/xiaoyuanxinwen/'+str(i)+'.html')

二.英文词频统计预处理

  代码如下:

file=open('artical.txt',encoding='utf-8')
text=file.read()
text=text.lower()
for i in str('?!,.'):
text=text.replace(i,'')
text=text.split()
dict={}
for i in text:
if i not in dict:
dict.update({i:text.count(i)})
for i in dict:
print(i+':',str(dict[i])+'次')

运行结果:

三.文件操作

1、凯撒密码:从文件读入密函,进行加密或解密,保存到文件。

代码如下:

if choice==1:
file=open('decrypt.txt','w',encoding='utf-8')
file.write(decrypt(text))
print(decrypt(text))
else:
file=open('encrypt.txt',encoding='utf-8')
text =file.read()[1:]
print(encrypt(text))


2、词频统计:下载一首英文的歌词或文章或小说,保存为utf8文件。从文件读入文本进行处理。

 代码如下:

file=open('artical.txt',encoding='utf-8')
text=file.read()

四.函数定义

1、加密函数

 代码如下:

 # 加密函数

def encrypt(text):
str=''
for i in text:
str=str+chr(ord(i)+3)
return str
 

2、解密函数

 代码如下:

# 解密函数
def decrypt(text):
str=""
for i in text:
str = str + chr(ord(i) - 3)
return str
原文地址:https://www.cnblogs.com/97lzc/p/10505589.html