【发布时间】:2011-07-20 00:31:15
【问题描述】:
请告知 - 我将以此作为学习点。我是初学者。
我将一个 25mb 的文件拆分成几个较小的文件。
这里的一位好心大师给了我一个 Ruby 脚本。它工作得非常快。所以,为了学习,我用 python 脚本模仿了它。这就像一只三足猫一样奔跑(慢)。我想知道是否有人可以告诉我为什么?
我的python脚本
##split a file into smaller files
###########################################
def splitlines (file) :
fileNo=0001
outFile=open("C:\\Users\\dunner7\\Desktop\\Textomics\\Media\\LexisNexus\\ele\\newdocs\%s.txt" % fileNo, 'a') ## open file to append
fh = open(file, "r") ## open the file for reading
mylines = fh.readlines() ### read in lines
for line in mylines: ## for each line
if re.search("Copyright ", line): # if the line is equal to the regex
outFile.close() ## close the file
fileNo +=1 #and add one to the filename, starting to read lines in again
else: # otherwise
outFile=open("C:\\Users\\dunner7\\Desktop\\Textomics\\Media\\LexisNexus\\ele\\newdocs\%s.txt" % fileNo, 'a') ## open file to append
outFile.write(line) ## then append it to the open outFile
fh.close()
大师的 Ruby 1.9 脚本
g=0001
f=File.open(g.to_s + ".txt","w")
open("corpus1.txt").each do |line|
if line[/\d+ of \d+ DOCUMENTS/]
f.close
f=File.open(g.to_s + ".txt","w")
g+=1
end
f.print line
end
【问题讨论】:
-
你能发布一些关于速度的数字吗?
-
脚本做不同的事情。 Python 脚本几乎会为它写入的每一行打开一个新文件。这当然很慢,但你期待什么?
-
Ruby 脚本还会打开多个文件进行输出。
-
但是只有在正则表达式匹配之后,python 脚本才真正做到每一行。
-
@Dat:但问题在于,ruby 脚本仅在匹配特定模式时才打开一个新文件,而 python 脚本会重新打开文件以附加到循环中的几乎每个迭代.