天天看點

字元串、檔案操作,英文詞頻統計預處理

作業要求來自于https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2646

1.字元串操作

  • 解析身份證号:生日、性别、出生地等
字元串、檔案操作,英文詞頻統計預處理
字元串、檔案操作,英文詞頻統計預處理
#解析廣州居民身份證号
str=input("請輸入你的廣州居民身份證号:")
gz=str[0:4]#市
dq=str[4:6]#區
year=str[6:10]#出生年
month=str[10:12]#出生月
day=str[12:14]#出生日
sex=str[14:17]#性别
j=0
if len(str) == 18:#驗證身份證長度是否正确
    if gz != '4401':
        print('該身份證号不屬于廣州居民!')
    else:
        num = ['03', '04', '05', '06', '11', '12', '13', '14', '84', '83', '15', '16']
        diqu = ['荔灣區', '越秀區', '海珠區', '天河區', '白雲區', '黃埔區', '番禺區', '花都區', '從化區', '增城區', '南沙區', '蘿崗區']
        for i in num:
            if dq == i:#比較地區是否存在
                if int(sex) % 2 == 0:#驗證性别
                    xingbie='女'
                else:
                    xingbie='男'
                print('你住在廣州市{},出生于{}年{}月{}日,性别為{}。'.format(diqu[j],year,month,day,xingbie))
                break
            else:
                j=j+1
        if j>len(diqu):#數組内已查找完無結果
            print('該身份證号有誤!')
else:
    print('你的身份證号碼有誤!')      

解析身份證号具體代碼

詳情結果如下:

字元串、檔案操作,英文詞頻統計預處理
  • 凱撒密碼編碼與解碼
字元串、檔案操作,英文詞頻統計預處理
字元串、檔案操作,英文詞頻統計預處理
def encryption():
  str_raw = input("請輸入明文:")
  s=ord('a')
  t=ord('z')
  print('加密結果為:')
  for i in str_raw:
    if s<=ord(i)<=t:
      print(chr(s+(ord(i)-s+3)%26),end='')#往後移三位
    else:
      print(i,end='')
def decryption():
  str_raw = input("請輸入密文:")
  s=ord('a')
  t=ord('z')
  print('加密結果為:')
  for i in str_raw:
     if s<=ord(i)<=t:
      print(chr(s+(ord(i)-s-3)%26),end='')#往前移三位
     else:
      print(i,end='')
while True:
  print (u"1. 加密")
  print (u"2. 解密")
  choice = input("請選擇:")
  if choice == "1":
    encryption()
  elif choice == "2":
    decryption()
  else:
    print (u"您的輸入有誤!")
  print('\n')      

凱撒密碼具體代碼

字元串、檔案操作,英文詞頻統計預處理
  • 網址觀察與批量生成
字元串、檔案操作,英文詞頻統計預處理
字元串、檔案操作,英文詞頻統計預處理
for i in range(2,10):
    url='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    print(url)      

網址批量生成具體代碼

詳細結果如下:

字元串、檔案操作,英文詞頻統計預處理

 2.英文詞頻統計預處理

  • 下載下傳一首英文的歌詞或文章或小說,儲存為utf8檔案。
字元串、檔案操作,英文詞頻統計預處理
  • 從檔案讀出字元串。
  • 将所有大寫轉換為小寫
  • 将所有其他做分隔符(,.?!)替換為空格
  • 分隔出一個一個的單詞
  • 并統計單詞出現的次數。
字元串、檔案操作,英文詞頻統計預處理
字元串、檔案操作,英文詞頻統計預處理
f=open(r'shape of you.txt','r')#打開相對路徑裡的文本
text=f.read()#讀取内容存到變量裡
print(text)#輸出文本内容
f.close()
lowerText=text.lower()#将文本裡所有字母轉化為小寫
sep=',?.!-:_'
for s in sep:
    text=text.replace(s,' ')#字元串裡的符号轉變成空格
print(lowerText.split())#按空格分隔單詞
print(text.count('come'),text.count('Come'),lowerText.count('come'))#統計原文的come和Come的詞頻,統計轉為小寫文本的come次數      

英文詞頻統計具體代碼

字元串、檔案操作,英文詞頻統計預處理
上一篇: 作業四