作業來源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2753
作業要求:
- 文字作業要求言簡意駭,用自己的話說明清楚。
- 編碼作業要求放上代碼,加好注釋,并附上運作結果截圖。
1.清單,元組,字典,集合分别如何增删改查及周遊。
- 清單:

增:
1 List = ['python','is','easy','to','learn']
2 List.append('100')
3 List
删:
4 del List[5]
5 List
改:
6 List[2] = 'hard'
查:
7 List
8 print("List[4]:",List[4])
周遊:
9 for i in List:
10 print ((List.index(i) + 1, i))

- 運作結果:
- 元組:

增(元組相加)
1 tup1 = ('python','is','easy','to','learn')
2 tup2 = (100,200)
3 tup3 = tup1 + tup2
4 print (tup3)
删:
5 del tup2
6 print(tup2)
查:
7 print("tup1[0]:",tup1[0])
周遊:
8 for item in tup1:
9 print(item)

- 字典:

增:
1 dict1 = {'python':'good','play':'nice','sport':'healthy'}
2 dict1['study']="pretty good"
3 dict1
删:
4 del dict1['play']
5 dict1
改:
6 dict1['study']="actually good"
7 dict1
查:
8 print("dict1['study']:",dict1['study'])
周遊:
9 for item in dict1.items():
10 print(item)

- 集合:

增:
1 set1 = {'python','is','easy','to','learn'}
2 set1.add('study')
3 set1
删:
4 set1.remove('to')
5 set1
查:
6 print("set1:",set1)
周遊:
7 for i in set1:
8 print (i)

2.總結清單,元組,字典,集合的聯系與差別。參考以下幾個方面:
- 括号、有序無序、可變不可變、重複不可重複、存儲與查找方式
清單是最常用的Python資料類型,它可以作為一個方括号内的逗号分隔值出現。清單的資料項不需要具有相同的類型,建立一個清單,隻要把逗号分隔的不同的資料項使用方括号括起來即可。清單也可以可以進行截取、組合,而向list中添加項有兩種方法:append和extend。
元組和清單在結構上沒有什麼差別,唯一的差異在于元組是隻讀的,不能修改。元組使用小括号,清單使用方括号。
集合(set)是一個無序的不重複元素序列。可以使用大括号 { } 或者 set() 函數建立集合,建立一個空集合必須用 set() 而不是 { },因為 { } 是用來建立一個空字典。
字典是另一種可變容器模型,且可存儲任意類型對象。字典的每個鍵值(key=>value)對用冒号(:)分割,每個對之間用逗号(,)分割,整個字典包括在花括号({})中。
3.詞頻統計
1.下載下傳一長篇小說,存成utf-8編碼的文本檔案 file
2.通過檔案讀取字元串 str
3.對文本進行預處理
4.分解提取單詞 list
5.單詞計數字典 set , dict
6.按詞頻排序 list.sort(key=lambda),turple
7.排除文法型詞彙,代詞、冠詞、連詞等無語義詞
- 自定義停用詞表
- 或用stops.txt
8.輸出TOP(20)
9.可視化:詞雲
排序好的單詞清單word儲存成csv檔案
import pandas as pd
pd.DataFrame(data=word).to_csv('big.csv',encoding='utf-8')
線上工具生成詞雲:
https://wordart.com/create
代碼如下:

1 import pandas as pd
2
3 article = open('article-long.txt', 'r', encoding='utf8')
4
5 # 排除詞彙清單
6 exclude = ['a', 'the', 'and', 'if', 'you', 'in', 'but', 'not', 'it', ' s', 'if', "i"]
7
8 # 打開文章函數getarticle
9 def getarticle():
10 sep = "'?', '?', '!'," '", "'", ' "', '"',':',':','.',',', ',', '.', '。','“','”',','"
11 text = article.read().lower()
12 for ii in sep:
13 text = text.replace(ii, ' ')
14 return text
15
16
17 articleList = getarticle().split()
18 articleDict = set(articleList)
19 exclude1 = set(exclude)
20 articleDict = articleDict-exclude1
21
22 # 統計單詞數量
23 countDict = {}
24 for word in articleDict:
25 countDict[word] = articleList.count(word)
26 print(countDict.items())
27 word = list(countDict.items())
28
29 # 排序單詞數量
30 word.sort(key=lambda x: x[1], reverse=True)
31 print(word)
32
33 # 輸出前二十位的單詞
34 for i in range(20):
35 print(word[i])
36
37 pd.DataFrame(data=word).to_csv('C:\\hungry-love.csv', encoding='utf-8')

運作結果:
- 輸出字典中的所有單詞及其出現次數并選取前20個:
複合資料類型,英文詞頻統計
生成csv檔案如下:
複合資料類型,英文詞頻統計
生成詞雲如下: