天天看點

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

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

1.字元串操作:

  • 解析身份證号:生日、性别、出生地等。
    字元串、檔案操作,英文詞率統計預處理
    字元串、檔案操作,英文詞率統計預處理
    1 idcard = input('請輸入身份證:')
     2 if len(idcard) == 18:
     3     birth = idcard[6:14]
     4     print('此身份證的生日是:',format(birth))
     5     sex = idcard[14:17]
     6     if int(sex) % 2 ==0:
     7         print('此身份證的性别為女')
     8     else:
     9         print('此身份證的性别為男')
    10 else:
    11     print('您輸入的身份證有誤')      
    View Code
    字元串、檔案操作,英文詞率統計預處理
    字元串、檔案操作,英文詞率統計預處理
  • 凱撒密碼編碼與解碼
    字元串、檔案操作,英文詞率統計預處理
    字元串、檔案操作,英文詞率統計預處理
    def encryption():
      str_raw = input("請輸入明文:")
      k = int(input("請輸入位移值:"))
      str_change = str_raw.lower()
      str_list = list(str_change)
      str_list_encry = str_list
      i = 0
      while i < len(str_list):
        if ord(str_list[i]) < 123-k:
          str_list_encry[i] = chr(ord(str_list[i]) + k)
        else:
          str_list_encry[i] = chr(ord(str_list[i]) + k - 26)
        i = i+1
      print ("加密結果為:"+"".join(str_list_encry))
    def decryption():
      str_raw = input("請輸入密文:")
      k = int(input("請輸入位移值:"))
      str_change = str_raw.lower()
      str_list = list(str_change)
      str_list_decry = str_list
      i = 0
      while i < len(str_list):
        if ord(str_list[i]) >= 97+k:
          str_list_decry[i] = chr(ord(str_list[i]) - k)
        else:
          str_list_decry[i] = chr(ord(str_list[i]) + 26 - k)
        i = i+1
      print ("解密結果為:"+"".join(str_list_decry))
    while True:
      print (u"1. 加密")
      print (u"2. 解密")
      choice = input("請選擇:")
      if choice == "1":
        encryption()
      elif choice == "2":
        decryption()
      else:
        print (u"您的輸入有誤!")      
    字元串、檔案操作,英文詞率統計預處理
  • 網址觀察與批量生成
    字元串、檔案操作,英文詞率統計預處理
    字元串、檔案操作,英文詞率統計預處理
    for i in range(1,20):
        url='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
        print(url)      
    字元串、檔案操作,英文詞率統計預處理

2.英文詞頻統計預處理

  • 下載下傳一首英文的歌詞或文章或小說,儲存為utf8檔案。
  • 從檔案讀出字元串。
  • 将所有大寫轉換為小寫
  • 将所有其他做分隔符(,.?!)替換為空格
  • 分隔出一個一個的單詞
  • 并統計單詞出現的次數。
    字元串、檔案操作,英文詞率統計預處理
    字元串、檔案操作,英文詞率統計預處理
    f = open(r'D:\pyhomework\bigbigword.txt',encoding='utf8')
    sep = ',./<>?`-_=+'
    text = f.read()
    print(text)
    f.close()
    text = text.lower()
    for i in sep:
        text = text.replace(i,' ')
    
        print(text.split())
        print(text.count('big'),text.count('world'))      
    字元串、檔案操作,英文詞率統計預處理