天天看點

複合資料類型,英文詞頻統計

作業部落格要求:

  • 文字作業要求言簡意駭,用自己的話說明清楚。
  • 編碼作業要求放上代碼,加好注釋,并附上運作結果截圖。

1.清單,元組,字典,集合分别如何增删改查及周遊。

(1)清單

list = ['a','b','hello',1]

 
#第一在清單後方添加資料 第二為在對應的下邊插入資料
list.append(2)
list.insert(0,'0')
print(list)      

        通過[]來建立清單,可通過索引(index)來擷取清單中的元素和修改元素;append() 方法向清單的最後添加一個元素,insert()向清單的指定位置插入一個元素,extend()使用新的序列來擴充目前序列,需要一個序列作為參數,它會将該序列中的元素添加到目前清單中;通過pop() 根據索引删除并傳回被删除的元素;一般通過for循環來周遊清單,如for s in stus :print(s)形式。

(2)元祖

       使用()來建立元組,它的操作的方式基本上和清單是一緻的。但元組是不可變的序列,不能嘗試為元組中的元素重新指派

(3)字典

       使用 {} 來建立字典,每一個元素都是鍵值對,鍵不重複,值可以重複。

(4)集合

       使用 {} 或set() 函數來建立集合,操作與字典類似,但隻包含鍵,而沒有對應的值,包含的資料不重複。可以通過set()來将序列和字典轉換為集合。

2.總結清單,元組,字典,集合的聯系與差別。參考以下幾個方面:

  • 括号
  • 有序無序
  • 可變不可變
  • 重複不可重複
  • 存儲與查找方式

(1)清單用[]表示,有序,可變,可重複,元素以值的方式存儲為值,可通過索引查找,如mylist[1]

(2)元組用()表示,有序,不可變,可重複,元素以值的方式存儲為值,可通過索引查找,如tuple[0]

(3)字典用{}表示,無序,鍵不可重複,值可以重複,元素以鍵值對的方式存儲為值,一般通過鍵查找,如dist['key']

(4)集合用{}表示,無序,可變,不可重複,元素以值的方式存儲為值,可以通過set()來将序列和字典轉換為集合。

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.可視化:詞雲
import pandas as pd
def getText():
    txt = open(r"E:\KING\PyCharm\KINGKING\big.txt", "rt").read()
    txt = txt.lower()
    for ch in '''’!@#$%^&*()_+=-';":.,<>/?|''':
        txt.replace(ch, " ")
    wordlist = txt.split()
    return wordlist

# 詞頻統計
wordlist = getText()
 # 過濾(排除文法詞彙,帶刺,冠詞,連詞等)
mum = {'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'}
wordset = set(wordlist) - mum

    # 字典
worddict = {}
for w in wordset:
    worddict[w] = wordlist.count(w)

    # 詞頻排序
    wordsort = list(worddict.items())
    wordsort.sort(key=lambda x: x[1], reverse=True)
for i in range(20):
    print(wordsort[i])
pd.DataFrame(data=wordsort).to_csv(r'E:\\KING\\大三(二)\\big.csv', encoding='utf-8')      

top20:

複合資料類型,英文詞頻統計

線上生成詞雲:

複合資料類型,英文詞頻統計

 排序好的單詞清單word儲存成csv檔案

import pandas as pd
pd.DataFrame(data=word).to_csv('big.csv',encoding='utf-8')

線上工具生成詞雲:
https://wordart.com/create