【问题标题】:How can I find acronym in a text?如何在文本中找到首字母缩写词?
【发布时间】:2015-12-06 23:00:12
【问题描述】:

我的项目读取了许多文件(这些文件具有标题文本和部分),并且应该找到包含首字母缩略词的文件的标题。这是我的文档类:

class Doc
  def initialize(id, secciones)
    @id, @secciones = id, secciones
  end
  def to_s
    result = "" + @id.to_s + "\n" + @secciones.to_s
    return result
  end
  def tiene_acronimo(acr)
    puts "a ver si tiene acronimos el docu.."
    tiene_acronimo = false
    secciones.each do |seccion|
      if seccion.tiene_acronimo(acr)
        tiene_acronimo = true
      end
    end
    return tiene_acronimo
  end
  attr_accessor :id
  attr_accessor :secciones
end

这是我的部分课程:

class Section
  def initialize ()
    @title = ""
    @text = ""   
  end
  def tiene_acronimo(acr)
    return title.include?(acr) || text.include?(acr)
  end
end

这是我的方法:

def test()
  results = Array.new
  puts "Dame el acronimo"
  acr = gets
  documentos_cientificos.each do |d|
  if d.tiene_acronimo(acr)
    results << d
  end  
end

该方法得到一个首字母缩写词,并且应该找到包含它的所有文档。 inclue? [sic] 方法会忽略大写并返回 true 如果文档包含任何子字符串(如首字母缩略词)。例如:

Multiple sclerosis (**MS**), also known as # => `true`
Presenting signs and sympto**ms** # => `false` (but `include?` returns `true`)

如何更轻松地找到首字母缩写词?

【问题讨论】:

    标签: ruby string include acronym


    【解决方案1】:

    您可以在 match 函数中使用一些正则表达式。如果内容包含提供的完整单词,则以下正则表达式将找到匹配项。它将忽略子字符串,并且区分大小写。

    arc = "MS"
    title = "Multiple sclerosis (MS), also known as"
    text = "Presenting signs and symptoms"
    
    title.match(/\b#{Regexp.escape(acr)}\b/) # => #<MatchData "MS">
    text.match(/\b#{Regexp.escape(acr)}\b/) # => nil
    

    或等效

    title.match(/\b#{Regexp.escape(acr)}\b/).to_a.size > 0 # => true
    text.match(/\b#{Regexp.escape(acr)}\b/).to_a.size > 0 # => false
    

    ...所以你可以将你的函数重新定义为:

    def tiene_acronimo(acr)
      regex_to_match = /\b#{Regexp.escape(acr)}\b/
      has_acr = false
      if (title.match(regex_to_match)) || (text.match(regex_to_match))
        has_acr = true
      end
    
      return has_acr
    end
    

    【讨论】:

    • 谢谢!我是 ruby​​ 的新手,当我声明 var acr =“MS”时,此代码有效,但是当我在屏幕上询问值时(“acr = gets”并且我输入 MS)不起作用。这很奇怪,因为我输入了相同的值......好像它们是不同的格式......谢谢:)
    • 当你使用gets时,一个换行符被附加到输入的末尾。您可以将行 regex_to_match = /\b#{Regexp.escape(acr)}\b/ 更改为 regex_to_match = /\b#{Regexp.escape(acr.strip)}\b/ 以去掉换行符,只需检查输入的文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多