簡體   English   中英

Ruby和RegExp

[英]Ruby and RegExp

對不起,如果已經問過了。

  • 我在psql中包含大約一百萬個文本文檔
  • 我正在嘗試查看它們是否包含某些單詞,例如癌症,死亡或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)

因此,我試圖在文本文件中搜索這些關鍵字,然后復制文本文檔。

任何幫助都非常感謝。

由於您說過:

我在psql中包含大約一百萬個文本文檔

並使用“ iLike”文本搜索運算符搜索這些文檔中的單詞。

恕我直言,這是一種效率低下的實現方式,因為您的數據量巨大,您的查詢將為每次搜索處理所有一百萬個文本文檔,而且速度非常慢。

在繼續之前,我認為您應該先閱讀PG 全文搜索 (如果您只是想在PG中使用內置的全文本搜索),或者您也可以查看一些其他專門針對文本搜索問題的產品,例如elasticsearch,solr等。

關於PG全文搜索,在Ruby中,您可以使用pg_serach gem。 但是,如果您使用Rails,我會寫一篇關於在Rails中使用PG進行簡單的全文本搜索的文章

希望您會覺得有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM