python入門 - 找到文件中出現次數最多的10個單詞

語言: CN / TW / HK

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)

```