pythonlist循环添加元素_python中 for循环之后 添加元素到列表失败?
import re
ls = list()
dc = dict()
# 介詞、連詞、人稱代詞等自己統(tǒng)計
adverb = ['i', 'you', 'he', 'she', 'it', 'in', 'on', 'with', 'by', 'for', 'at', 'about', 'under', 'of', 'to', 'and',
'or',
'therefore', 'so', 'of', 'a']
with open("老人與海.txt", mode='r', encoding='utf-8') as f:
lryh = f.read() # 打開文件并讀取
for i in lryh.split(' '): # 按空格分隔,即獲取單個詞語,
res=re.match(r'[a-zA-Z]+$',i)
if res:
i=i.lower()
if i not in adverb: # 這個單詞不再adverb列表中,則添加到ls中
ls.append(i)
else: # 如果匹配出錯,就結束這次循環(huán),這個else,寫不寫的無所謂了,反正是最后面的循環(huán)語句
continue
# i = i.lower() # 轉成全部是小寫字母,為后面的判斷提供方便
# if i.isalpha() and i not in adverb: # 如果是字母組成的詞語并且不再adverb列表中的
# ls.append(i) # 保存在ls列表中
for item in ls:
dc[item] = ls.count(item) # 統(tǒng)計ls列表中單詞出現次數,并保存到dc字典中。
sorted_dc = sorted(dc.items(), key=lambda b: b[1], reverse=True) # 按字典的value值進行降序排序
print('前十個出現頻率最高的單詞:')
for item in sorted_dc[0:10]:
print(item[0], end='\t')
print('\n')
for key, value in sorted_dc[0:10].__iter__():
print('%s出現了%s次' % (key, value))
總結
以上是生活随笔為你收集整理的pythonlist循环添加元素_python中 for循环之后 添加元素到列表失败?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 性感网名154个
- 下一篇: python写入数据到excel_pyt