【发布时间】:2011-01-07 16:11:42
【问题描述】:
我的一个朋友写了这个小程序。
textFile 大小为 1.2GB(价值 7 年的报纸)。
他成功地创建了字典,但无法使用 pickle 将其写入文件(程序挂起)。
import sys
import string
import cPickle as pickle
biGramDict = {}
textFile = open(str(sys.argv[1]), 'r')
biGramDictFile = open(str(sys.argv[2]), 'w')
for line in textFile:
if (line.find('<s>')!=-1):
old = None
for line2 in textFile:
if (line2.find('</s>')!=-1):
break
else:
line2=line2.strip()
if line2 not in string.punctuation:
if old != None:
if old not in biGramDict:
biGramDict[old] = {}
if line2 not in biGramDict[old]:
biGramDict[old][line2] = 0
biGramDict[old][line2]+=1
old=line2
textFile.close()
print "going to pickle..."
pickle.dump(biGramDict, biGramDictFile,2)
print "pickle done. now load it..."
biGramDictFile.close()
biGramDictFile = open(str(sys.argv[2]), 'r')
newBiGramDict = pickle.load(biGramDictFile)
提前致谢。
编辑
对于任何有兴趣的人,我将简要解释这个程序的作用。
假设您的文件格式大致如下:
<s>
Hello
,
World
!
</s>
<s>
Hello
,
munde
!
</s>
<s>
World
domination
.
</s>
<s>
Total
World
domination
!
</s>
-
<s>是句子分隔符。 - 每行一个字。
生成一个 biGramDictionary 供以后使用。
像这样:
{
"Hello": {"World": 1, "munde": 1},
"World": {"domination": 2},
"Total": {"World": 1},
}
希望这会有所帮助。现在策略改为使用 mysql,因为 sqlite 不起作用(可能是因为大小)
【问题讨论】:
-
如果您要处理大文件,为什么不使用数据库呢?另外,我看到你在同一个文件上循环了 2 次,这可能是多余的并增加了处理成本。为什么不描述您对示例输入文件所做的事情?
-
ghostdog74,你看到 2 个 for 语句,但文件上只有一个循环 :) 迭代文件只是读取行(从实际位置),它不会寻找到开头文件。
-
只需尝试sqlitedict(您的 Python 字典由磁盘上的 DB 支持,而不是 RAM)。
标签: python file dictionary pickle