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

这个作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2620

1.字符串操作:

  • 解析身份证号:生日、性别、出生地等。
    • 代码如下
    • # -*- coding: utf-8 -*-
      def isSex(idSex):
          if int(idSex)%2==1:
              print("性别为:男")
          else:
              print('性别为:女')
      
      idCard = input("请输入身份证号码:")
      if len(idCard) != 18:
          isTure = 0
          while(isTure == 0):
              idCard = input('身份证位数有误!!!请重新输入:')
              if len(idCard) == 18:
                  isTure =1
      print('地址信息为:%s'% idCard[:6])
      print('生日为:{0}年{1}月{2}日'.format(idCard[6:10],idCard[10:12],idCard[12:14]) )
      isSex(idCard[16:17])
    • 运行效果
  • 凯撒密码编码与解码
    • 在密码学中,恺撒密码是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。网址观察与批量生成
    • 偏码代码如下:
    • # -*- coding: utf-8 -*-
      pianMa = ""
      text = input("请输入要编码的话:")
      for s in text:
          pianMa = pianMa + chr(ord(s)+3)
      print(pianMa)

      运行效果

    • 解码代码如下

    • # -*- coding: utf-8 -*-
      pianMa = ""
      text = input("请输入要编码的话:")
      for s in text:
          pianMa = pianMa + chr(ord(s)-3)
      print(pianMa)

      运行效果如下

代码如下

# -*- coding: utf-8 -*-
import  webbrowser as web
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
web.open_new_tab(url)
for i in range(2,4):
     print('http://news.gzcc.cn/html/xiaoyuanxinwen/'+str(i)+'.html')

打开网址效果

网址生成效果如下:

2.英文词频统计预处理

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

代码如下:

# -*- coding: utf-8 -*-
# 读取文件

f = open("wenzhang.txt","r")
text = f.read()
f.close()

# 转为小写
text = text.lower()
# 将所有其他做分隔符(,.?!)替换为空格
text = text.replace(","," ").replace("."," ").replace("?"," ").replace("!"," ")
# 分割为单词
text = text.split()

print("our的个数为:",text.count("our"))

运行结果如下:

原文地址:https://www.cnblogs.com/hesz/p/10485424.html