首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >活动记录文本匹配

活动记录文本匹配
EN

Stack Overflow用户
提问于 2014-09-01 04:01:41
回答 1查看 53关注 0票数 0

我试图使用活动记录在Ruby中进行一些基本的文本匹配。

代码语言:javascript
复制
Here is my code so far;

require 'active_record'
require 'yaml'
require 'pg'
require 'pry'
require 'FileUtils'

$config = '
adapter: postgresql
database: edgar
username: YYYYY
password:
host: 127.0.0.1'

ActiveRecord::Base.establish_connection(YAML::load($config))
class Doc    < ActiveRecord::Base; end
class Eightk < ActiveRecord::Base; end



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

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


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}..."


death.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
end

我有一个很长的条件清单,我想寻找;

  1. 有没有办法让我把搜索列表组合起来。我试过“癌症”--“死亡”--但没有任何运气
  2. 我想对单词做一个精确的匹配,而不是喜欢,但我不知道命令,

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-01 04:13:31

也许就像

代码语言:javascript
复制
keywords = %w(cancer death anotherone)
records = Eightk.where keywords.map{|w| "(text ILIKE '%#{w}%')"}.join(' OR ')

records.each do |filing|
  filename = "#{directory}/#{filing.doc_id}.html"
  File.open(filename,"w").puts filing.text
end

否则,您可以使用“类似于”或“POSIX”http://www.postgresql.org/docs/8.1/static/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP,然后您可以使用正则表达式。

例如

代码语言:javascript
复制
Eightk.where "text SIMILAR TO '%(#{keywords.join '|' })%'"

POSIX允许您检查单词的开始和结束,这样您可以只检查一个完整的单词匹配(例如在,deathdeathdeath.上匹配,而不是deathbed等)。

我会把regex的东西留给有更好regex的人。)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25598679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档