python 統計檔案中的字串數目示例
阿新 • • 發佈:2020-01-09
題目:
一個txt檔案中已知資料格式為:
C4D
C4D/maya
C4D
C4D/su
C4D/max/AE
統計每個欄位出現的次數,比如C4D、maya
先讀取檔案,將檔案中的資料抽取出來:
def getWords(filepath): file = open(filepath) wordOne=[] while(file): line = file.readline() word = line.split('/') wordOne.extend(word) if(not line): #若讀取結束了 break wordtwo=[] for i in wordOne: wordtwo.extend(i.split()) return wordtwo
說明:這個有一個要注意的地方是檔案是被”\n”,”/”兩種格式分割而來的,因此需要split兩次。
然後定義一個dict,遍歷資料,程式碼如下所示:
def getWordNum(words): dictWord={} for i in words: if(i not in dictWord): dictWord[i]=0 dictWord[i]+=1 return dictWord
主函式的呼叫:
filepath='data/new.txt' words = getWords(filepath) dictword = getWordNum(words) print(dictword)
結果:
{'C4D': 9,'max': 1,'su': 1,'maya': 1,'AE': 3}
說明:
1,
print(type(word)) print(type(splitData[0]))
輸出為:
<class 'list'> <class 'str'>
就是當splitData.extend()執行之後就將原本是list型別的資料轉換成str型別的儲存起來。只有對str型別的資料才能用split函式
2,
import os print(os.getcwd())
這個可以輸出當前所在位置,對於讀取檔案很有用。
在讀入檔案並對檔案進行切分的時候,若是含有的切分詞太多,那麼使用re.split()方法是最方便的,如下所示:
filepath='data/new.txt' file = open(filepath) #讀取檔案 wordOne=[] symbol = '\n/' #定義分隔符 symbol = "["+symbol+"]" #拼接正則表示式 while(file): line = file.readline() word = re.split(symbol,line) wordOne.extend(word) if(not line): break #通過上式得到的list中會含有很多的空字串,所以要去空 wordOne = [x for x in wordOne if x]
以上這篇python 統計檔案中的字串數目示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。