1. 程式人生 > >組合數據類型練習,英文詞頻統計實例

組合數據類型練習,英文詞頻統計實例

news forever .com 分隔 ima hat http war nis

實例:由字符串創建一個作業評分列表,做增刪改查詢統計遍歷操作。
例如,查詢第一個3分的下標
統計1分的同學有多少個,3分的同學有多少個

>>> ap=list("0213023021321320132132131231")
>>> ap
[0, 2, 1, 3, 0, 2, 3, 0, 2, 1, 3, 2, 1, 3, 2, 0, 1, 3, 2, 1, 3, 2, 1, 3, 1, 2, 3, 1]
>>> ap.append(4)
>>> ap [0, 2, 1, 3, 0, 2, 3, 0, 2, 1, 3, 2, 1, 3, 2, 0, 1, 3, 2, 1, 3, 2, 1, 3, 1, 2, 3, 1, 4] >>> ap.pop(2) 1 >>> ap [0, 2, 3, 0, 2, 3, 0, 2, 1, 3, 2, 1, 3, 2, 0, 1, 3, 2, 1, 3, 2
, 1, 3, 1, 2, 3, 1, 4] >>> ap.index(3) 2 >>> ap.count(1) 7 >>> ap.count(3) 8 >>>

字典實例:建立學生學號成績字典,做增刪改查遍歷操作。

>>> d={"1":"李家秀","29":"李韶豪","18":"劉卓暉","30":"曾國建"}
>>> print(d)
{1: 李家秀, 29: 李韶豪, 18: 劉卓暉, 30: 
曾國建} >>> d["4"]="吳敏敏" >>> print(d) {1: 李家秀, 29: 李韶豪, 18: 劉卓暉, 30: 曾國建, 4: 吳敏敏} >>> d["29"] 李韶豪 >>> del(d[1]) >>> d {29: 李韶豪, 18: 劉卓暉, 30: 曾國建, 4: 吳敏敏}>>> d.values() dict_values([李韶豪, 劉卓暉, 曾國建, 吳敏敏]) >>> d.items() dict_items([(29, 李韶豪), (18, 劉卓暉), (30, 曾國建), (4, 吳敏敏)]) >>> d.get(30,ll) 曾國建 >>> d {29: 李韶豪, 18: 劉卓暉, 30: 曾國建, 4: 吳敏敏} >>> d.pop(30,ll) 曾國建 >>> d {29: 李韶豪, 18: 劉卓暉, 4: 吳敏敏} >>>

列表,元組,字典,集合的遍歷。
總結列表,元組,字典,集合的聯系與區別。

>>> a=list("132132002031323")
>>> a
[1, 3, 2, 1, 3, 2, 0, 0, 2, 0, 3, 1, 3, 2, 3]
>>> b=tuple("1321320321")
>>> b
(1, 3, 2, 1, 3, 2, 0, 3, 2, 1)
>>> c = {apple:1, banana:2, orange:3}
>>> c
{apple: 1, banana: 2, orange: 3}
>>> d=set("23132321321320001")
>>> d
{2, 3, 0, 1}
>>> for i in a:
    print(i)

    
1
3
2
1
3
2
0
0
2
0
3
1
3
2
3
>>> for i in b:
    print(i)

    
1
3
2
1
3
2
0
3
2
1
>>> for i in c:
    print(i,c[i])

    
apple 1
banana 2
orange 3
>>> for i in d:
    print(i)

    
2
3
0
1
>>> 

英文詞頻統計實例

  1. 待分析字符串
  2. 分解提取單詞
    1. 大小寫 txt.lower()
    2. 分隔符‘.,:;?!-_’
  3. 計數字典
  4. 排序list.sort()
  5. 輸出TOP(10)

sr=‘‘‘Just one last dance ,oh baby just one last dance!
We meet in the night in the Spanish café,
I look in your eyes just don‘t know what to say,
It feels like I‘m drowning in salty water,A few hours left ‘til the sun‘s gonna rise,
tomorrow will come an it‘s time to realize.our love has finished forever,
how I wish to come with you!how I wish we make it through!
Just one last dance!before we say goodbye,
when we sway and turn round and round and round,
it‘s like the first time,Just one more chance,
hold me tight and keep me warm.cause the night is getting cold.
and I don‘t know where I belong,Just one last dance! ‘‘‘

news =sr.lower()
for i in ,.:
    news=news.replace(i, )
words=news.split( )
print(words)
dic={}
keys=set(words)
for i in keys:
    dic[i]=words.count(i)
wc=list(dic.items())
wc.sort(key = lambda x:x[1],reverse=True)
for i in range(10):
    print(wc[i])

技術分享

組合數據類型練習,英文詞頻統計實例