本次做業要求來自於:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2753app
1.列表,元組,字典,集合分別如何增刪改查及遍歷。函數
列表:經過[]來建立列表,可經過索引(index)來獲取列表中的元素和修改元素;append() 方法向列表的最後添加一個元素,insert()向列表的指定位置插入一個元素,extend()使用新的序列來擴展當前序列,須要一個序列做爲參數,它會將該序列中的元素添加到當前列表中;經過pop() 根據索引刪除並返回被刪除的元素;通常經過for循環來遍歷列表,如for s in stus :print(s)形式。工具
元組:使用()來建立元組,它的操做的方式基本上和列表是一致的。但元組是不可變的序列,不能嘗試爲元組中的元素從新賦值學習
字典:使用 {} 來建立字典,每個元素都是鍵值對,鍵不重複,值能夠重複。可經過索引爲其添加或修改元素dict['key']='value';通常經過del(del dict['key'])或pop()方法(dict.pop('key'))刪除,其中pop(key[, default]),根據key刪除字典中的key-value,會將被刪除的value返回,若是刪除不存在的key,會拋出異常。clear()用來清空字典;能夠經過遍歷keys()來獲取全部的鍵, for k in d.keys() :print(k , d[k]),或經過items()方法遍歷字典;如for k,v in d.items() :print(k , '=' , v)spa
集合:使用 {} 或set() 函數來建立集合,操做與字典相似,但只包含鍵,而沒有對應的值,包含的數據不重複。能夠經過set()來將序列和字典轉換爲集合。code
2.總結列表,元組,字典,集合的聯繫與區別。參考如下幾個方面:blog
列表用[]表示,有序,可變,可重複,元素以值的方式存儲爲值,可經過索引查找,如mylist[1]排序
元組用()表示,有序,不可變,可重複,元素以值的方式存儲爲值,可經過索引查找,如tuple[0]索引
字典用{}表示,無序,鍵不可重複,值能夠重複,元素以鍵值對的方式存儲爲值,通常經過鍵查找,如dist['key']utf-8
集合用{}表示,無序,可變,不可重複,元素以值的方式存儲爲值,能夠經過set()來將序列和字典轉換爲集合。
3.詞頻統計
# 讀文本,獲取單詞函數
def get_text(file): f = open(file, 'r', encoding='utf8') text = f.read() f.close() # 將全部大寫轉換爲小寫
text = text.lower() # re表示待替換的符號
re = '.?!:\"\',\n'
# 將全部其餘作分隔符替換爲空格
for i in re: text = text.replace(i, ' ') # 分隔出一個一個的單詞
words_list = text.split() return words_list
# 詞頻統計函數
def get_wordsort(words_list): # 排除語法型詞彙,代詞、冠詞、連詞等無語義詞
reps = {'it', 'if', 'the', 'at', 'for', 'on', 'and', 'in', 'to', 'of', 'a', 'was', 'be', 'were','in','about','from','with','without','an','one','another'
,'others','that','they','himself','itself','themselves','if','when','before','though','although','while','as','as long as','i','he','him','she',
'out','is','s','no','not','you','me','his','but'} words_set = set(words_list) - reps # 存入字典
words_dict = {} for w in words_set: words_dict[w] = words_list.count(w) # 字典轉換成列表對單詞進行詞頻排序
words_sort = list(words_dict.items()) words_sort.sort(key=lambda x: x[1], reverse=True) return words_sort
# 調用get_text函數得到一個個單詞列表
words_list = get_text('D:\\學習\\oldManAndFish.txt') # 調用詞頻統計函數get_wordsort得到從高到低的單詞列表
words_sort = get_wordsort(words_list) # 導入pandas包使用DataFrame方法對words_sort詞頻列表轉換成csv文件保存
import pandas as pd pd.DataFrame(data=words_sort).to_csv(r'D:\\學習\\story.csv',encoding='utf-8')
執行代碼生成:
利用story.csv文件生成單詞TOP(20):
利用線上工具生成詞雲: