【问题标题】:Slow python file I:O; Ruby runs better than this; Got the wrong language?慢python文件I:O; Ruby 比这运行得更好;语言有误?
【发布时间】: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 脚本会重新打开文件以附加到循环中的几乎每个迭代.

标签: python ruby regex text


【解决方案1】:

您的脚本运行缓慢的原因有很多——主要原因是您几乎为您编写的每一行都重新打开了输出文件。由于旧文件在打开新文件时会隐式关闭(由于 Python 垃圾收集),写入缓冲区会为您写入的每一行刷新,这非常昂贵。

脚本的清理和更正版本将是

def file_generator():
    file_no = 1
    while True:
        f = open(r"C:\Users\dunner7\Desktop\Textomics\Media"
                 r"\LexisNexus\ele\newdocs\%s.txt" % file_no, 'a')
        yield f
        f.close()
        file_no += 1

def splitlines(filename):
    files = file_generator()
    out_file = next(files)
    with open(filename) as in_file:
        for line in in_file:
            if "Copyright " in line:
                out_file = next(files)
            out_file.write(line)
        out_file.close()

【讨论】:

  • +1 弄清楚这段代码迫使我学习了一些我以前不知道的较新的 python 特性。我喜欢 SO 的众多原因之一。
  • 只是着迷有人必须弄清楚我的代码!我是个缩水!!,觉得我应该换职业???不,好的。
  • @Rosser - 不是你的代码 - 很明显那里出了什么问题。我以前没有见过 Sven 用于读取文件的 with as 构造。它对 python 来说不是超级新的,但我以前没有遇到过。
【解决方案2】:

我猜你的脚本这么慢的原因是你为每一行打开了一个新的文件描述符。如果您查看 guru 的 ruby​​ 脚本,它只会在您的分隔符匹配时关闭并打开输出文件。

与此相反,您的 python 脚本会为您读取的每一行打开一个新的文件描述符(顺便说一句,不会关闭它们)。打开一个文件需要和内核对话,所以比较慢。

我建议的另一个改变是改变

fh = open(file, "r") ## open the file for reading
mylines = fh.readlines() ### read in lines
for line in mylines: ## for each line

到

fh = open(file, "r")
for line in fh:

通过此更改,您无需将整个文件读入内存,而是一个块接一个块。虽然对于 25MiB 的文件应该没关系,但是对于 big 文件会伤害到你,这是一种很好的做法(而且代码更少;))。

【讨论】:

    【解决方案3】:

    Python 代码可能会因为正则表达式而不是 IO 而变慢。试试

    def splitlines (file) :
      fileNo=0001
      outFile=open("newdocs/%s.txt" % fileNo, 'a') ## open file to append 
      reg = re.compile("Copyright ")
      for line in open(file, "r"): 
        if reg.search("Copyright ", line): # if the line is equal to the regex
          outFile.close()  ##  close the file
          outFile=open("newdocs%s.txt" % fileNo, 'a') ## open file to append 
          fileNo +=1  #and add one to the filename, starting to read lines in again
    
        outFile.write(line)          ## then append it to the open outFile          
    

    几点说明

    • 始终使用 / 而不是 \ 作为路径名
    • 如果重复使用正则表达式,编译它
    • 您需要重新搜索吗?还是重新匹配?

    更新:

    • @埃德。 S:点数
    • @Winston Ewert:代码更新为更接近原始 Ruby 代码

    【讨论】:

    • 对少量文本应用正则表达式比从磁盘读取文件慢的那一天就是我停止使用正则表达式的那一天。我认为你对这个的猜测是错误的。
    • 如果修改代码不要经常重新打开文件,会快很多。
    【解决方案4】:

    罗瑟,

    不要在代码(文件、分割线)中使用内置对象的名称作为标识符

    以下代码尊重您自己代码的效果:一个out_file被关闭,没有包含构成关闭信号的'Copyright'的行

    writelines() 函数的使用旨在获得比重复 out_file.write(line) 更快的执行速度

    if li: 块用于触发 out_file 的关闭,以防读取文件的最后一行不包含“版权”

    def splitfile(filename, wordstop, destrep, file_no = 1, li = []):
        with open(filename) as in_file:
            for line in in_file:
                if wordstop in line:
                    with open(destrep+str(file_no)+'.txt','w') as f:
                        f.writelines(li)
                    file_no += 1
                    li = []
                else:
                    li.append(line)
            if li:
                with open(destrep+str(file_no)+'.txt','w') as f:
                    f.writelines(li)
    

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 2011-05-02
      • 2018-06-16
      • 1970-01-01
      • 2012-11-24
      • 2012-05-24
      • 1970-01-01
      • 2018-06-15
      相关资源
      最近更新 更多