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

作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2684

1.字符串操作

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

  代码展示

复制代码
#coding=utf-8

#身份证解析
code=input("请输入您的身份证号:")
province=code[0:2]
city=code[2:4]
county=code[4:6]
year=code[6:14]
month=code[10:12]
day=code[12:14]
print("您的生日为:{}年{}月{}日".format(year,month,day))
print("您的出生地为:{}省{}市{}县".format(province,city,county))
复制代码

  运行效果

  • 凯撒密码编码与解码

  代码展示

复制代码
#coding=utf-8

#凯撒密码
text=input("请输入需要加密的的明文:")
cip = '';mw = ''
for i in text:
  cip += chr(ord(i)+6)
print("明文加密后为:",cip)
for i in cip:
  mw += chr(ord(i)-6)
print("密文解密后为:",mw)
复制代码

  运行效果

  • 网址观察与批量生成

  代码展示

#网址批量生成
for i in range(2,6):
  print('https://www.liaoxuefeng.com/%d.html',i)

  运行效果

2.英文词频统计预处理

  • 下载一首英文的歌词或文章或小说。
  • 将所有大写转换为小写
  • 将所有其他做分隔符(,.?!)替换为空格
  • 分隔出一个一个的单词
  • 并统计单词出现的次数。

  代码展示

复制代码
#词频统计
print("词频统计")
file=open("bin.txt")
text=file.read();
file.close();
s=",.?!"
for i in s:
  text=text.replace(i," ")
  text=text.lower().split()
print(text)
count={}
for i in text:
  try:
    count[i]=count[i]+1
  except KeyError:
    count[i]=1
print(count)
复制代码

  运行效果

3.文件操作

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

  代码展示

#coding=utf-8

file=open("bin1.txt",'r')
text=file.read();
file.close;
cip = '';
for i in text:
  cip += chr(ord(i)+6)
print("明文加密后为:",cip)
file=open("bin1.txt",'w')
file.write(cip);
file.close()
复制代码

  运行效果

  • 词频统计:

  下载一首英文的歌词或文章或小说,保存为utf8文件,从文件读入文本。

  代码展示

复制代码
#coding=utf-8

file=open("bin.txt")
text=file.read();
file.close();
s=",.?!"
for i in s:
  text=text.replace(i," ")
  text=text.lower().split()
print(text)
count={}
for i in text:
  try:
    count[i]=count[i]+1
  except KeyError:
    count[i]=1
print(count)
复制代码

  运行效果

4.函数定义

  • 加密函数

  代码展示

#coding=utf-8

def jiami(text):
result='';
for i in text:
  result=result+chr(ord(i)+6)
return result
  • 解密函数

  代码展示

复制代码
#coding=utf-8

def jiemi(text):
result='';
for i in text:
  result=result+chr(ord(i)+6)
return result
复制代码
  • 读文本函数

  代码展示

#coding=utf-8

def read(text):
  file=open(text,'r')
return file.read();
原文地址:https://www.cnblogs.com/binguo666/p/10505318.html