我在幾個文檔中遍歷數十萬個單詞,希望找到英語收縮頻率。我已經適當地格式化了文件,現在是編寫正確的功能並正確存儲數據的問題。我需要爲每個發現收縮的文檔存儲信息,以及它們在文檔中的使用頻率。理想情況下,我的數據幀看起來像以下:迭代文檔時存儲3個不同的變量(字典或列表)?
filename contraction count
file1 it's 34
file1 they're 13
file1 she's 9
file2 it's 14
file2 we're 15
file3 it's 4
file4 it's 45
file4 she's 13
我怎樣才能最好的去嗎?
編輯:這是我的代碼,迄今:
for i in contractions_list: # for each of the 144 contractions in my list
for l in every_link: # for each speech
count = 0
word_count = 0
content_2 = processURL_short(l)
for word in content2.split():
word = word.strip(p)
word_count = word_count + 1
if i in contractions:
count = count + 1
凡processURL_short()
是一個功能我寫的擦傷一個網站,並返回一個講話str
。
EDIT2:
link_store = {}
for i in contractions_list_test: # for each of the 144 contractions
for l in every_link_test: # for each speech
link_store[l] = {}
count = 0
word_count = 0
content_2 = processURL_short(l)
for word in content_2.split():
word = word.strip(p)
word_count = word_count + 1
if word == i:
count = count + 1
if count: link_store[l][i] = count
print i,l,count
這是我的文件命名代碼:
splitlink = l.split("/")
president = splitlink[4]
speech_num = splitlink[-1]
filename = "{0}_{1}".format(president,speech_num)
總輸入流量有多大?用發生器流提供字典可能是您的最佳解決方案。 – Prune
如果我正確理解輸入流的意思,那麼有900個文本文件流(全部不超過25000個字,平均大約10000個),並且在我的字典中有144個縮寫 – blacksite
正確。在這種情況下,此時不需要更改其他代碼。如果您確實獲得了更大的文件,請考慮學習如何編寫Python生成器(請參閱** yield **語句),並且可以在不犧牲很多速度(通常在10%,有時更快)的情況下節省運行時內存。 – Prune