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

 一.字符串操作

 

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

 

代码如下:

#解析身份证生日、性别、出生地等
s="445222199709042213"
print("")
print("生日:"+s[6:14])
print("性别:"+s[-2])
print("出生地:"+s[0:6])

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:解码\n2:加密')
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 as web
url="http://news.gzcc.cn/html/xiaoyuanxinwen/"
web.open_new_tab(url)
for i in range(1,2):
    web.open_new_tab(url+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

posted on 2019-03-11 19:51  liliguang  阅读(174)  评论(0编辑  收藏  举报