我写了一个脚本,基本上把一个句子中的所有字符串分成几个部分
例如:
"geldigim" -> "gel" "di" "g" "i" "m"
有些字符串可以按上述方式拆分,有些字符串可以按以下方式拆分
"bildi" > "bil" "di"
或者有些句子可能根本就不分开。你知道吗
"kos" -> "kos"
它完全是由一个函数决定的,这个函数将字符串分成几个部分。你知道吗
我想做的是:
geldigim -> /gel* *di* *g* *i* *m/
bildi -> /bil* *di/
kos -> /kos/
我所做的是
我有一个语料库,有37251512个句子。我写了以下脚本
if __name__ == "__main__":
io = morfessor.MorfessorIO()
print "Importing corpus ..."
f = codecs.open("corpus/corpus_tr_en/corpus.tr", encoding="utf-8").readlines()
print "Importing morphology model ..."
model = io.read_binary_model_file('seg/tr/model.bin')
corpus = open('dataset/dataset_tr_en/full_segmented.tr', 'w')
for a in range(len(f)):
print str(a) + ' : ' + str(len(f))
words = f[a].replace('\n', '').split()
line_str = ''
for word in words:
segmentation = model.viterbi_segment(word)[0]
if len(segmentation) == 1:
line_str = '/' + segmentation[0] + '/'
if len(segmentation) == 2:
line_str = '/' + segmentation[0] + '* *' + segmentation[1] + '/'
if len(segmentation) > 2:
line_str = ''
for b in range(len(segmentation)):
if (b == 0):
line_str = line_str + '/' + segmentation[b] + '*'
if (b != 0) and (b != (len(segmentation) - 1)):
line_str = line_str + ' *' + segmentation[b] + '* '
if (b == (len(segmentation) - 1)):
line_str = line_str + ' *' + segmentation[b] + '/'
line_str = line_str + ' '
corpus.write(line_str.encode('utf-8'))
corpus.write('\n')
corpus.close()
这个脚本在每个句子和句子中的每个单词上循环,并使用io.read_binary_model_file
函数将其拆分为多个部分。你知道吗
但对我来说太贵了,太慢了。你知道吗
你能给我建议一个使过程非常快的方法吗?你知道吗
谢谢你
使用多个字符串连接的
line_str
的组合可能会减慢很多速度,如果您想要性能,不建议使用多个字符串连接(对于filename = base+".txt"
之类的内容,这是可以的,但对于密集处理则不是。你知道吗将
line
创建为list
,然后使用str.join
创建最后一个字符串以将其写入磁盘。附加到list
要快得多。你知道吗正如Maximilian刚才所建议的,您可以将您的条件转换为
elif
,因为它们是相互排斥的(x2)。还添加了一些微优化,以提高可读性以及。你知道吗我建议你的内环应该是什么样子:
备选方案:
io.StringIO
对象并检索它以写入输出文件。你知道吗这样的内环怎么样:
那么,既然你可以同时把输入保存在内存中,我也会尽量把输出保存在内存中,一次就写出来,可能是这样的:
readlines()
。只需使用for a in f
,有关详细说明,请参见here。你知道吗range
.replace('\n', '').split()
很慢,因为当您只想删除最后一个换行符时,它必须在整行上循环(在您的情况下不能有多个换行符)。你可以用^{/
结尾,但您有3个位置。你知道吗相关问题 更多 >
编程相关推荐