python入門 - 找到文件中出現次數最多的10個單詞
title: python入門 - 找到文件中出現次數最多的10個單詞 tags: python categories: python theme: vue-pro highlight:
最近有點需求,在看python的入門基礎,看完入門基礎之後,跟着練習,找到文件中出現次數最多的10個單詞,以此熟悉語法。
語法概要
mac電腦命令行輸入python3
,回車可以執行語句,exit()
退出
python3 xx.py
可以執行文件。
- 初始賦值,一般用
None
- 聲明變量不需要任何多餘,沒有
var
/const
巴拉巴拉 - 語法用
:
表示一起,縮進
表示嵌套關係 - 字典就是對象,用
dict()
新建,注意dict({'a':1})
必須要用引號括起來鍵 - 字典獲取值的時候,鍵必須存在不然會報錯,一般用
xxDict.get('a',0)
來獲取,這樣沒有就賦值0,有就獲取 - 列表就是數組,用
list()
新建,注意不能獲取超過list長度的索引,如果取局部的話xxList[0:10]
這樣就行 - 元組,在js中沒有,雖然ts中有,元組類似列表,但不能編輯,表示為
(1,2)
,如果你的列表不需要編輯,就可以用元組替換 - sorted可以排序的方法,排序數組、對象的key、元組,通常排序對象的時候,如果需要排序value的話,可以用
sorted(([(v,k) for (k,v) in xxDict.items()]))
快速得到排序後的元組列表,從大到小的話,第二參數加上reverse=True
- 打開文件
open(filepath)
,但返回值不是字符串,需要for line in open(filepath)
,拿到每行的文本 - 字符串變成數組,用
split
,默認分隔符是空格 try: expect:
關鍵語句,記得捕獲錯誤,需要的話退出程序quit()
代碼
```python
本文件是獲取 任意文件裏出現次數前10的word
藉此學習python的簡單數據結構
python3 xx.py 執行就可以
filename = input('文件的路徑:')
這裏用户輸入的文件路徑可能打不開,所以try下,如果出錯,程序退出
try: # 打開文件,獲取文件手柄 handle = open(filename) except: print('File Cannot be opened',filename) quit()
countDict = dict()
遍歷文件的每行,line就是每行的字符串
for line in handle: # 空格為分隔符,得到每行的單詞列表 words = line.split() # 遍歷每行的單詞列表,word是每個單詞 for word in words: # 此行相當於,沒有key的話,新建key取0,有的話返回 countDict[word] = countDict.get(word,0) + 1 # 等同於 # # word沒出現在dic的話,需要賦值,不然讀的話會報錯 # if word not in countDict : # countDict[word] = 0 # # 處理完之後,都加1 # countDict[word] = countDict[word] + 1
得到各單詞出現的次數字典
print(countDict)
最大出現的次數
bigCount = None
最大出現的次數對應的word
bigKey = None
遍歷字典,key就是word,value就是次數
for word in countDict: count = countDict[word] # 注意None的情況和大於的情況都需要賦值 if bigCount is None or count>bigCount: bigCount = count bigKey = word
print(bigCount)
print(bigKey)
python的字典key必須是字符串包裹
a = dict({'a':1,'b':2})
items字典會返回元組列表 [('a', 1), ('b', 2)]
print(a.items())
sorted排序元組列表
將countDict變成元組列表,然後將k,v對調,變成新元組列表
sortList = sorted(([(count,word) for (word,count) in countDict.items()]),reverse=True)
等同於以下
# 裝(value,key)的list
tempList = list()
# 遍歷countDict.items(),能同時獲取key,value
for (word,count) in countDict.items():
# key value調換下位置
newTuple = (count,word)
# 裝進tempList
tempList.append(newTuple)
# sorted 排序元組的時候,先按照元組的第一項排序,這邊就是按照count排序,且從大到小
sortList = sorted(tempList,reverse=True)
取前10
tenList = sortList[0:10]
還需要將key和value反轉回來
resDict = dict() for (count,word) in tenList: resDict[word] = count
print(resDict)
```
- 微信中打開自家APP - 現成按鈕組件來了!
- 跳轉別人的頁面,怎麼加個返回呢
- python入門 - 找到文件中出現次數最多的10個單詞
- 怎麼修改請求的參數和響應
- 簡單學習SQL語言
- h函數為什麼叫h?
- 簡單的DOM的相關總結
- 細心使用es6的語法
- 理解執行上下文和其生命週期
- JS內存管理生命週期和垃圾回收機制
- 從0實現簡易版的vuex
- watch經常失效的場景和解決方案
- 讓el-table更好用,通過配置的方式
- 讓el-form更好用,通過配置的方式
- 寫個簡單css動畫,transition 和animate
- 怎麼封裝彈框組件
- 手寫實現el-form系列組件的核心邏輯 -- 練習組件通信
- 怎麼使用async-validator快速校驗表單
- 作用域插槽slot的使用場景 -- vue組件通信系列
- $parent/$children的使用場景 -- vue組件通信系列