Re: [問題] 函式寫入txt
※ 引述《harohepowegr (harohepowegr)》之銘言:
: 先讀入兩個txt檔
: b1
: This is a book
: This is a pen
: This is a table
: This is a desk
: b2
: This is a papaya
: This is a pineapple
: This is a banana
: This is a melon
我想這是一個計算每個單字(以空格作斷詞)的一隻程式。
以下是我自己的意見提供你參考,也歡迎大家討論 ~
: 以下為程式碼
: #讀檔函式
: def readbook(filename):
: readin = open(filename)
: count = []
: for line in readin:
: letter = line.split()
: count = count + letter
: return count
首先,如果是增加一個 list 內的元素,可以善用 .append(), .extend()
這邊可以改寫成 count.extend(line.split())
def readbook(filename):
count = []
with open(filename) as f:
for line in f:
count.extend(line.split())
return count
: #計算出現次數
: def list2dict(count):
: ldict = dict()
: for ch in count:
: ldict[ch]=ldict.get(ch,0)+1
: return ldict
用 dict 計算詞頻,可以善用 Python standard library 中的 collections.Counter
https://docs.python.org/3/library/collections.html#collections.Counter
此段程式碼可以用 return Counter(count) 來取代
Counter 有非常多好用的功能,包含他相加就是次數的相加,不存在的 key 會回傳 0,
提供 .most_common() 的詞頻排序功能…(請看官網說明)
在這邊能用 Counter.update() 的函式來更新詞頻,可以傳入 list 或者 dict
: book1 = readbook('b1.txt')
: book2 = readbook('b2.txt')
: text = list2dict(book1+book2)
: print('全部出現的單字和次數')
: print(list2dict(book1+book2))
因此整隻程式可以改寫成:
from collections import Counter
word_freq = Counter(readbook('b1.txt'))
word_freq.update(readbook('b2.txt'))
print(word_freq)
為什麼寫入的內容不一樣,你可以試試以下的函式:
with open('output.txt', 'w') as f:
f.write(str(word_freq))
細節可以再想想~
再來講斷詞的部份。這些程式碼可以寫得再簡單一點,
在 readbook 中可以用雙層的 list comprehension 來完成:
with open(filename) as f:
return Counter(
[wd for line in f for wd in line.split()]
)
或者,他根本可以是一個 generator
return Counter(
w for l in f for w in line.split()
)
以上~
--
>>>>>> PyCon APAC 2014/TW <<<<<<
手把手課程 PlaY Data 與 Intro to Django 熱烈報名中!
詳情請見 https://tw.pycon.org/2014apac/zh/tutorial/
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.217.22
※ 文章網址: http://www.ptt.cc/bbs/Python/M.1398425034.A.7C1.html
※ 編輯: ccwang002 (140.112.217.22), 04/25/2014 19:29:26
推
04/25 20:07, , 1F
04/25 20:07, 1F
→
04/25 20:15, , 2F
04/25 20:15, 2F
推
04/26 00:28, , 3F
04/26 00:28, 3F
推
04/26 17:29, , 4F
04/26 17:29, 4F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章