天天看點

【大資料應用技術】作業二 |字元串操作,英文詞頻統計預處理

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

1.字元串操作

(1)解析身份證号:生日、性别、出生地等

 ① 代碼

1 # -*- coding: utf-8 -*-
 2 
 3 ID=input('請輸入18位省份證号碼:');
 4 if len(ID) == 18:
 5     print("你輸入的身份證号碼為"+ID);
 6 else:
 7     print("你輸入的身份證号碼有誤!");
 8 
 9 ID_add = ID[0:6]; #ID_add 指的是身份證的區域代碼
10 ID_birth = ID[6:14]; #ID_birth 指的是出生年月
11 ID_sex = ID[14:17]; #ID_sex 指的是性别
12 
13 #出生年月
14 year = ID_birth[0:4];
15 month = ID_birth[4:6];
16 day = ID_birth[6:8];
17 print("你的出生日期為:"+year+"年"+month+"月"+day+"日");
18 
19 #性别
20 if int(ID_sex)%2 == 0:
21     print("性别:女");
22 else:
23     print("性别:男");      

② 運作結果

【大資料應用技術】作業二 |字元串操作,英文詞頻統計預處理

(2)凱撒密碼編碼與解碼

1 # -*- coding: utf-8 -*-
 2 import os
 3 
 4 alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
 5 #1.編碼
 6 def get_code():
 7     print('請輸入要編碼的字元:');
 8     s=input();
 9     str1='';
10     for i in range(len(s)):
11         if s[i] in alphabet:
12             #temp=ord(s[i]);
13             #num=(temp-97+3)%26;
14             #str1=chr(num+97);
15             str1 = alphabet[(ord(s[i])-97+3)%26];
16             print(str1,end="");
17         else:
18             print(" ",end="");
19 
20 #2.解碼
21 def decode():
22     print('請輸入要解碼的字元:');
23     s = input();
24     str2 = '';
25     for i in range(len(s)):
26         if s[i] in alphabet:
27             str2 = alphabet[(ord(s[i])-97-3)%26];
28             print(str2, end="");
29         else:
30             print(" ", end="");
31 
32 while True:
33     print("\n");
34     print('1.編碼');
35     print('2.解碼');
36     choice = input("請輸入1或者2進行選擇:");
37     if choice == '1':
38         get_code();
39     elif choice == '2':
40         decode();
41     else:
42         print('輸入錯誤!');      
【大資料應用技術】作業二 |字元串操作,英文詞頻統計預處理

(3)網址觀察與批量生成

1 # -*- coding: utf-8 -*-
2 
3 for i in range(2,6):
4         url='http://xybgs.gzcc.cn/html/xuxigg/{}.html'.format(i);
5         print(url);      
【大資料應用技術】作業二 |字元串操作,英文詞頻統計預處理

2.英文詞頻統計預處理

① 英文文章

在這裡我将文章放在了跟源代碼檔案同級的路徑上

② 源代碼

1 f=open('test.txt','r',encoding='utf8');
 2 article=f.read();
 3 f.close();
 4 
 5 article = article.lower();
 6 sep = ".-,:";
 7 for s in sep:
 8     article=article.replace(s,' ');
 9 print(article.split(' '));
10 print(article.count('friend'));      

③ 運作結果

【大資料應用技術】作業二 |字元串操作,英文詞頻統計預處理