作業要求來自于https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2696
1.清單,元組,字典,集合的增删改查及周遊
操作 | 方法 | 示例 |
增加 | list.append(obj) 增加元素到末尾 | ![]() append |
list.insert(index, obj) 增加元素到指定位置 | ![]() insert | |
list.extend(list2) 将list2清單中的元素增加到list中 | ![]() entend | |
删除 | list.pop(index) 删除指定位置的元素 list.pop() 删除最後一個元素 | ![]() pop |
修改 | list[index]=obj 修改指定位置的元素 | ![]() list[]=obj |
查詢 | list[index] 通過下标索引,從0開始 | ![]() list[] |
list[a:b] 切片,從哪裡到哪裡 | ![]() | |
周遊 | for x in list | ![]() |
for i in range(len(list)) | ![]() | |
for i,val in enumerate(list) | ![]() for i, val in enumerate(list) | |
for i in list | ![]() |
tup=tup1+tup2 元組不支援修改,但可以通過連接配接組合的方式進行增加 | ![]() tup1+tup2 | |
del tup 元組不支援單個元素删除,但可以删除整個元組 | ![]() | |
tup[index]=obj 元組和清單轉換 | ![]() | |
tup[index] | ![]() | |
tup[a:b] 切片,顧頭不顧尾 | ![]() | |
for x in (tup) | ![]() |
dict[key]=value 通過指派的方法增加元素 | ![]() dict[key] | |
del dict[key] 删除單一進制素,通過key來指定删除 | ![]() del dict[] | |
dict.pop(key) | ![]() dict.pop() | |
通過對已有的key重新指派的方法修改 | ![]() | |
通過key通路value值 | ![]() | |
dict.items() 以清單傳回可周遊的(鍵, 值) 元組數組 | ![]() | |
dict.keys() 以清單傳回一個字典所有鍵值 dict.values() 以清單傳回一個字典所有值 | ![]() dict.keys(),dict.values() | |
dict.get(key) 傳回指定key的對應字典值,沒有傳回none | ![]() dict.get() | |
for key in dict.keys() | ![]() | |
for val in dict.values() | ![]() | |
for key,val in dict.items() | ![]() for key, val in dict.items() |
s.add(obj) 在集合s中添加對象obj | ![]() s.add() | |
s.remove(obj) 從集合s中删除對象obj | ![]() s.remove() | |
s[index]=obj 集合和清單轉換 | ![]() | |
for x in s | ![]() |
2.總結清單,元組,字典,集合的聯系與差別
(1)清單
- 清單list,用中括号“[ ]”表示
- 清單是一組任意類型的值,按照一定順序組合而成的
- 可以随時添加删除修改其中的元素
- 元素可重複
- 存儲時每一個元素被辨別一個索引,每當引用時,會将這個引用指向一個對象,是以程式隻需處理對象的操作
(2)元組
- 元組tuple,用小括号“( )”表示
- 與清單相同,有序
- 一旦初始化就不能修改
- 與清單相似,元組是對象引用的數組
(3)字典
- 字典dict,用大括号“{key,value}”表示
- 字典中的項沒有特定順序,以“鍵”為象征
- 因為是無序,故不能進行序列操作,但可以在遠處修改,通過鍵映射到值
- key不能重複
- 字典存儲的是對象引用,不是拷貝,和清單一樣
(4)集合
- 集合set,用小括号“( )”表示
- 無序
- 可變,可以添加和删除元素
- 無重複
- 與清單相似
3.詞頻統計

# import nltk
# nltk.download("stopwords")
from nltk.corpus import stopwords
stops=set(stopwords.words('english'))
#通過檔案讀取字元串 str,對文本進行預處理
def gettxt():
sep=".,:;?!-_'"
txt=open('Crimes and Punishments.txt','r', encoding='UTF-8').read().lower()
for ch in sep:
txt=txt.replace(ch,' ')
return txt
#分解提取單詞 list
txtList=gettxt().split()
print(txtList)
print('crimes:',txtList.count('crimes'))
txtSet=set(txtList)
#排除文法型詞彙,單詞計數字典 set , dict
txtSet=txtSet-stops
print(txtSet)
txtDict={}
for word in txtSet:
txtDict[word]=txtList.count(word)
print(txtDict)
print(txtDict.items())
word=list(txtDict.items())
#按詞頻排序 list.sort(key=lambda),turple
word.sort(key=lambda x:x[1],reverse=True)
print(word)
#輸出頻率較高的詞語top20#
for i in range(20):
print(word[i])
#排序好的單詞清單word儲存成csv檔案
import pandas as pd
pd.DataFrame(data=word).to_csv('Crimes and Punishments.csv',encoding='utf-8')
詞頻統計具體代碼
結果如下圖:
詞雲如下圖: