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

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

元組 one lam 主鍵 必須 分析字符串 logs with spa

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

d={‘10‘:80,‘11‘:87,‘13‘:76,‘13‘:50,‘14‘:89,‘15‘:96,‘16‘:89,‘17‘:100}
d[‘40‘]=95#增加學號為40
print(d)
d.pop(‘17‘)#刪除學號為17的
print(d)
d[‘11‘]=60#修改學號為11的
print(d)
d.get(‘15‘)
print(d)

運行結果:技術分享

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

lis = list(‘10086‘)

tup = tuple(‘10010‘)

d = dict(zip([1,2,3,4],[7,8,9,10]))
s = set(lis)

print(‘遍歷列表:‘)
for i in lis:
print(i)

print(‘遍歷元組:‘)
for i in tup:
print(i)

print(‘遍歷字典:‘)
for i in d:
print(i)

print(‘遍歷集合:‘)
for i in s:
print(i)

運行結果

技術分享

1.列表,元組,字典是有順序的,而集合是沒順序的

2.列表是以方括號形式表示,元組是以圓括號表示,字典以花括號表示,集合則是以[()]的形式表示,是一個無序不重復元素集,基本功能包括關系測試和消除重復元素

3.列表是可變對象,它支持在原處修改的操作.也可以通過指定的索引和分片獲取元素。區別於元組,可動態增加,刪除,更新。

4.元組和列表在結構上沒有什麽區別,唯一的差異在於元組是只讀的,不能修改。元組用“()”表示。元組一旦定義其長度和內容都是固定的。一旦創建元組,則這個元組就不能被修改,即不能對元組進行更新、增加、刪除操作。若想創建包含一個元素的元組,則必須在該元素後面加逗號“,”,否則創建的不是一個元組,而是一個字符串。

3.英文詞頻統計實例

A.待分析字符串

B.分解提取單詞

a.大小寫 txt.lower()

b. 分隔符‘.,:;?!-_’

c.單詞列表

C單詞計數字典

sorry=‘‘‘You gotta go and get angry at all of my honesty
You know I try but I don’t do too well with apologies
I hope I don’t run out of time, could someone call a referee?
Cause I just need one more shot at forgiveness
I know you know that I made those mistakes maybe once or twice
By once or twice I mean maybe a couple a hundred times
So let me, oh let me redeem, oh redeem, oh myself tonight
Cause I just need one more shot at second chances
Yeah, is it too late now to say sorry?
Cause I’m missing more than just your body
Is it too late now to say sorry?
Yeah I know that I let you down
Is it too late to say I’m sorry now?
I’m sorry, yeah
Sorry, yeah
Sorry
Yeah I know that I let you down
Is it too late to say sorry now?
I’ll take every single piece of the blame if you want me to
But you know that there is no innocent one in this game for two
I’ll go, I’ll go and then you go, you go out and spill the truth
Can we both say the words and forget this?
Is it too late now to say sorry?
Cause I’m missing more than just your body
Is it too late now to say sorry?
Yeah I know that I let you down
Is it too late to say I’m sorry now?
I’m not just trying to get you back on me
Cause I’m missing more than just your body
Is it too late now to say sorry?
Yeah I know that I let you down
Is it too late to say sorry now?
I’m sorry, yeah
Sorry, oh
Sorry
Yeah I know that I let you down
Is it too late to say sorry now?
I’m sorry, yeah
Sorry, oh
Sorry
Yeah I know that I let you down
Is it too late to say sorry now?‘‘‘
sorry=sorry.lower()
for i in ‘?,‘:
sorry=sorry.replace(i,‘ ‘)#全部小寫
words=sorry.split(‘ ‘)#以空格分隔
print(words)

dic={}#定義一個空字典
words.sort()#排列切片好的單詞
d=set(words)#集合d的元素就是切片好的單詞

for i in d:
dic[i]=0#循環插入值為空的主鍵i

for i in words:
dic[i]=dic[i]+1#利用循環計算主鍵個數
print(dic)

技術分享

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