如何使用Faker生成标题和真实的英语文本

时间:2019-11-29 19:24:01

标签: ruby faker

我的数据库中有一个名为posts的表,每条记录代表一个带有titleurlbody的帖子。

是否可以使用Faker生成英文标题和正文?正文应为实际的英文文本。

我浏览了文档,但没有找到想要的东西。

1 个答案:

答案 0 :(得分:1)

对于英文文本,为什么不能这样做?

Faker::Quote.matz
=> "I believe that the purpose of life is, at least in part, to be happy. Based on this belief, Ruby is designed to make programming not only easy but also fun. It allows you to concentrate on the creative side of programming, with less stress."

或尝试:

Faker::Hipster.sentences.sample
=> "Cornhole drinking actually pop-up brooklyn williamsburg wayfarers."

对于标题,只需

[Faker::Company.name,  Faker::Company.industry].join(' - ')
=> "Schmitt-Kohler - E-Learning"

但是,如果您确实需要一些随机的实际句子,可以将它们从随机的书本中提取出来,在这里使用正则表达式可以获取包含在双引号中的句子。

string = `curl http://www.textfiles.com/etext/FICTION/alger-cast-544.txt`
regex = /(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)/
sentences = string.to_enum(:scan, regex).map {$&}
puts sentences.sample

在这里,您可以从文本文件中获取任何句子。

class String
  def split_sentence
    ary = self.gsub(/\n/," ").split(/([^\.\?\!]+[\.\?\!])/)
    ary.delete("")
    sentences = Array.new
    str = ""
    for i in 0..ary.size-1
      next if ary[i].size == 0 || ary[i] =~ /^\s*$/
      str << ary[i]
      next if str =~ /Mr|Mrs|Ms|Dr|Mt|St\.$/
      if (i < ary.size-1)
        next if ary[i] =~ /[A-Z]\.$/
        next if ary[i+1] =~ /^\s*[a-z]/
      end
      if ary[i+1] =~ /^\"/
        str << '"'
        ary[i+1].sub!(/^\"/,"")
      elsif ary[i+1] =~ /^\)/
        str << ')'
        ary[i+1].sub!(/^\)/,"")
      end
      sentences << str.sub(/^\s+/,"")
      str = ""
    end
    sentences
  end
end

string = `curl http://www.textfiles.com/etext/FICTION/alger-cast-544.txt`
puts string.split_sentence.sample