How to change … (elipses) to … (three periods) in Ruby?

我怕爱的太早我们不能终老 提交于 2019-12-07 07:25:30

问题


I'm parsing this document using nokogiri. I found there are some (elipses) characters in that page and can't be removed. I want to know how to use Ruby to replace all (elipses) to ... (three periods).

BTW, you can search this string to find all …s

Specifies whether ALTER TABLE

Edit: I added my program and the error message.

# encoding: UTF-8
require 'nokogiri'
require 'open-uri'
require 'terminal-table'

def change s
    {Nokogiri::HTML(" ").text => " ", 
     Nokogiri::HTML(""").text => '"',
     Nokogiri::HTML("™").text => '(TM)',
     Nokogiri::HTML("&").text => "&",
     Nokogiri::HTML("&lt;").text => "<",
     Nokogiri::HTML("&gt;").text => ">",
     Nokogiri::HTML("&copy;").text => "(C)",
     Nokogiri::HTML("&reg;").text => "(R)",
     Nokogiri::HTML("&yen;").text => " "}.each do |k, v|
         s.gsub!(k, v)
     end
     s
end

doc = Nokogiri::HTML(open('http://msdn.microsoft.com/en-us/library/ms189782.aspx').read.tr("…","..."))
temp = []
doc.xpath('//div[@class="tableSection"]/table[position() = 1]/tr').each do |e|
    temp << e.css("td, th").map(&:text).map(&:strip).map {|x| x = change x; x.split(/\n/).map {|z| z.gsub(/.{80}/mi, "\\0\n")}.join("\n")}
end

table = Terminal::Table.new
table.headings = temp.shift
table.rows = temp


puts table

Error:

F:\dropbox\Dropbox\temp>ruby nokogiri.rb
nokogiri.rb:21: invalid multibyte char (UTF-8)
nokogiri.rb:21: invalid multibyte char (UTF-8)
nokogiri.rb:21: syntax error, unexpected $end, expecting ')'
...ary/ms189782.aspx').read.tr("í¡","..."))
...                               ^

F:\dropbox\Dropbox\temp>

回答1:


It probably depends on the encoding of the file you're working with, but try using

"\u2026"

for the single-character 3-dots aka "horizontal ellipsis" (the one you want to replace).




回答2:


"It was a dark and stormy night…".gsub("…", "...")



回答3:


I'd just String#tr on it first.

open("http://msdn.microsoft.com/en-us/library/ms189782.aspx").read.tr("…","...")

And run Nokogiri on that...



来源:https://stackoverflow.com/questions/9421524/how-to-change-elipses-to-three-periods-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!