我有以下功能:化功能的使用字典和Zip()
def filetxt():
word_freq = {}
lvl1 = []
lvl2 = []
total_t = 0
users = 0
text = []
for l in range(0,500):
# Open File
if os.path.exists("C:/Twitter/json/user_" + str(l) + ".json") == True:
with open("C:/Twitter/json/user_" + str(l) + ".json", "r") as f:
text_f = json.load(f)
users = users + 1
for i in range(len(text_f)):
text.append(text_f[str(i)]['text'])
total_t = total_t + 1
else:
pass
# Filter
occ = 0
import string
for i in range(len(text)):
s = text[i] # Sample string
a = re.findall(r'(RT)',s)
b = re.findall(r'(@)',s)
occ = len(a) + len(b) + occ
s = s.encode('utf-8')
out = s.translate(string.maketrans("",""), string.punctuation)
# Create Wordlist/Dictionary
word_list = text[i].lower().split(None)
for word in word_list:
word_freq[word] = word_freq.get(word, 0) + 1
keys = word_freq.keys()
numbo = range(1,len(keys)+1)
WList = ', '.join(keys)
NList = str(numbo).strip('[]')
WList = WList.split(", ")
NList = NList.split(", ")
W2N = dict(zip(WList, NList))
for k in range (0,len(word_list)):
word_list[k] = W2N[word_list[k]]
for i in range (0,len(word_list)-1):
lvl1.append(word_list[i])
lvl2.append(word_list[i+1])
我已經使用Profiler來發現它似乎是最大的CPU時間都花在zip()
功能和join
和split
代碼的一部分,我期待看看是否有任何方式我忽略了我可能會清理代碼以使其更加優化,因爲最大的滯後似乎是我如何使用字典和zip()
功能。任何幫助,將不勝感激謝謝!
p.s.這個函數的基本目的是我加載的文件中包含20個左右的推文,所以我最有可能最終會通過這個函數發送大約20k到50k個文件。輸出結果是我在推文中產生了所有不同單詞的列表,然後是哪些單詞鏈接到什麼,例如:
1 "love"
2 "pasa"
3 "mirar"
4 "ants"
5 "kers"
6 "morir"
7 "dreaming"
8 "tan"
9 "rapido"
10 "one"
11 "much"
12 "la"
...
10 1
13 12
1 7
12 2
7 3
2 4
3 11
4 8
11 6
8 9
6 5
9 20
5 8
20 25
8 18
25 9
18 17
9 2
...
非常感謝我基本上從你和@milkypostman拿走了一些,但如果有人因爲某種原因尋找一個較短的答案,我會將其標記爲答案。另外我犯的最大錯誤是調用`W2N = dict(zip(WList,NList))`,它每循環一遍又一遍地製作一個更大更大的字典,並且浪費了cpu時間。解決的辦法是把它放在循環之外。過去需要5分鐘的1000個文件現在需要0.5秒左右的時間。 – eWizardII 2011-01-10 08:22:41