【发布时间】:2019-01-12 03:20:16
【问题描述】:
我正在使用 Python 64 位获得MemoryError。这是我的功能:
def entr_langue(path,nom_langue):
mots_ts=[]
table_tr=dict((ord(char),None) for char in string.punctuation)#table de translation/mapping
with codecs.open(path,"r","utf-8") as filep:
for i,line in enumerate(filep):
#extraction par ligne
line=" ".join(line.split()[1:])
line=line.lower()
line=re.sub(r"\d+"," ",line) #suppression des digits
if len(line) !=0:
line=line.translate(table_tr)#suppression des poncts
mots_ts += line
mots_ts.append(" ")#ajout des espaces
ts_str=''.join(mots_ts)
ts_str=re.sub(' +',' ',ts_str) #remp des series d'espaces par un seul espace
seq_ts=[i for i in ts_str]
#daba extraction des Bigram et les trier selon la frequ
fn=BigramCollocationFinder.from_words(seq_ts)
fn.apply_freq_filter(6) #"li 3ndhom frequ 9el m 6 ytfiltraw
bigram_model=fn.ngram_fd.viewitems()
bigram_model=sorted(fn.ngram_fd.viewitems(), key=lambda item: item[1],reverse=True)
print (bigram_model)
np.save(nom_langue+".npy",bigram_model)
错误:
File "C:/Users/msi/Documents/projIA/extraction_bigram.py", line 23, in entr_langue
mots_ts += line
MemoryError
【问题讨论】:
-
您的输入文件有多大,可用的 RAM 有多少?
-
mots_ts += line这行效率很低。将.append()和.extend()用于列表。 -
您可能还需要安装 64 位版本的 NLTK(或在安装 64 位版本的 Python 后重新安装)。
-
@KlausD.:
lists 重载+=使其在很大程度上等同于extend。也就是说,OP 应该在这里使用append进行一个不错的更改;因为line是str,+=(和extend)都会单独添加line中的每个字符,并且他们可能只是希望将整行作为单个值。 -
旁注:各位,请停止使用
codecs.open。 It's buggy, slow, and unnecessary on Python 2.6 and higher, whereio.openis available。在 Py3 上,open是io.open的别名,在 Py2 上,io.open基本上是codecs.open的正确、高效版本。with io.open(path,encoding="utf-8"):是你想要的。