2014-09-03 54 views
1

对不起,如果这已被问到。Ruby和RegExp

  • 我有我想看看他们是否含有某些字包含在PSQL
  • 大约100万的文本文件,例如癌症,或死亡或heart_attack等,这名单也相当长。
  • 该文件只需要包含一个单词。
  • 如果他们包含一个词,我然后尝试将它们复制到一个不同的文件夹。

我当前的代码是:

directory = "disease"  #Creates a directory called heart attacks 
    FileUtils.mkpath(directory) # Makes the directory if it doesn't exists 

    cancer = Eightk.where("text ilike '%cancer%'") 
    died = Eightk.where("text ilike '%died%'") 

    cancer.each do |filing| #filing can be used instead of eightks 
    filename = "#{directory}/#{filing.doc_id}.html" 
    File.open(filename,"w").puts filing.text 
    puts "Storing #{filing.doc_id}..." 


    died.each do |filing|  #filing can be used instead of eightks 
    filename = "#{directory}/#{filing.doc_id}.html" 
    File.open(filename,"w").puts filing.text 
    puts "Storing #{filing.doc_id}..." 

    end 

但是这是行不通的以下

  • 不匹配确切的词

  • 自从它非常耗时以来,它非常耗时有很多应对相同的代码,只改变一个词。

所以我一直在使用Regexp.union如下尝试,但感到有点失落

directory = "disease"  #Creates a directory called heart attacks 
    FileUtils.mkpath(directory)  # Makes the directory if it doesn't exists 


    keywords = [/dead/,/killed/,/cancer/] 

    re = regexp.union(keywords) 

所以我试图寻找这些关键字的文本文件,然后复制文本文档。

任何帮助真的很感激。

回答

1

既然你说:

我已经包含在PSQL

,并使用“iLike的”文本搜索运算符搜索词在这些文件大约有100万的文本文档。

恕我直言,这是一个效率低下的实现,因为您的数据是巨大的,您的查询将处理所有100万文本文件为每个搜索,它会很慢。

在继续前进之前,我认为你应该首先看一下PG Full Text Searching。 (如果您只是想在PG中使用内置的全文搜索),或者您还可以查看一些其他产品,如弹性搜索,solr等,这些产品专用于文本搜索问题。

关于PG全文搜索,在Ruby中,您可以使用pg_serach宝石。虽然,如果您使用Rails,我可以使用关于在Rails中使用PG的简单全文搜索实现。

我希望你会觉得这很有用。