对于我的毕业论文,我需要创建一个扑克行为数据集来测试模型。我编写了一个函数,该函数读取包含有关手的信息的文本文件并返回list
,并将其附加到熊猫数据框。
我大约有1500个文件,每个文件都需要传递1500〜3000个手,因此我的主脚本看起来像这样。
import os
os.chdir("C:/Users/jctda/OneDrive/Documentos/TCC/Programa")
import pandas as pd
from datagen import DataGenerator, EmptyLine
from poker.room.pokerstars import PokerStarsHandHistory
from functions import FindFold, GetFiles, GetShowers
#IMPORT DATAGEN AQUI
database = pd.DataFrame()
files = GetFiles('hand_texts')
for hand_text in files:
text=open('hand_texts/' + hand_text)
b=text.read()
hands=b.split("\n\n\n\n\n")
text.close()
for i in range(1,len(hands)):
try:
hh = PokerStarsHandHistory(unicode(hands[i]))
hh.parse()
fold = FindFold(hh)
if fold == 'showdown':
for shower in GetShowers(hh):
database = database.append(DataGenerator(hh,shower,hand_text,i))
print('Success in parsing iteration ' + str(i) + ' from file' + hand_text)
except:
print('PARSER ERROR ON ITERATION [[' + str(i) + ']] FROM FILE [[' + hand_text + ']]')
database = database.append(EmptyLine(hand_text,i))
database.to_csv('database2.csv')
问题在于,运行几个小时后,它变得非常缓慢。第一个文件大约需要20秒,但是每次都变慢,并且运行8小时后,每个文件开始花费一个多小时。我刚刚开始为该项目学习python,所以我可能在某个地方犯了一个大错误,导致它花费了比所需更多的时间,但我找不到它。
困扰我的另一件事是,当它在具有16GB的计算机上运行时,它消耗不到1GB的RAM。我曾想过要强迫它使用更多的内存,但显然对python没有内存限制,所以我想那只是不好的代码
有人可以帮我弄清楚怎么办吗?
正如在描述这里,不附加到数据帧在循环中,因为它是非常inefficent。宁愿做这样的事情:
files = GetFiles('hand_texts')
database = []
for hand_text in files:
# as a sidenote, with contexts are helpful for these:
with open('hand_texts/' + hand_text) as text:
b=text.read()
hands=b.split("\n\n\n\n\n")
for i in range(1,len(hands)):
try:
hh = PokerStarsHandHistory(unicode(hands[i]))
hh.parse()
fold = FindFold(hh)
if fold == 'showdown':
for shower in GetShowers(hh):
database.append(DataGenerator(hh,shower,hand_text,i))
print('Success in parsing iteration ' + str(i) + ' from file' + hand_text)
except:
print('PARSER ERROR ON ITERATION [[' + str(i) + ']] FROM FILE [[' + hand_text + ']]')
database.append(EmptyLine(hand_text,i))
pd.DataFrame(database).to_csv('database2.csv'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句