0

我正在尝试使用此处记录的 rmmseg-cpp gem 的示例代码:http ://rmmseg-cpp.rubyforge.org/#Stand-Alone-rmmseg

只是为了测试它,我把它放在 show.html.erb 中,如下所示:

# coding: UTF-8
<p id="notice"><%= notice %></p>

<p>
  <b>Title:</b>
  <%= @lesson.title %>
</p>

<p>
  <b>Content:</b>
  <%= @lesson.content %> # simplified chinese text
</p>

<p><% require 'rmmseg' %>
<% algor = RMMSeg::Algorithm.new(@lesson.content) %>
<% loop do %>
  <% tok = algor.next_token %>
  <% break if tok.nil? %>
  <%= "#{tok.text} [#{tok.start}..#{tok.end}]" %>
<% end %> </p>

<%= link_to 'Edit', edit_lesson_path(@lesson) %> |
<%= link_to 'Back', lessons_path %>

我收到以下错误:

 Encoding::CompatibilityError in Lessons#show

Showing /Users/webmagnets/rails_projects/blt/app/views/lessons/show.html.erb where line #19 raised:

incompatible character encodings: UTF-8 and ASCII-8BIT

Extracted source (around line #19):

16: <% loop do %>
17:   <% tok = algor.next_token %>
18:   <% break if tok.nil? %>
19:   <%= "#{tok.text} [#{tok.start}..#{tok.end}]" %>
20: <% end %> </p>
21: 
22: <%= link_to 'Edit', edit_lesson_path(@lesson) %> |

Rails.root: /Users/webmagnets/rails_projects/blt
Application Trace | Framework Trace | Full Trace

app/views/lessons/show.html.erb:19:in `block in _app_views_lessons_show_html_erb___3831310028264182552_70339844987120'
app/views/lessons/show.html.erb:16:in `loop'
app/views/lessons/show.html.erb:16:in `_app_views_lessons_show_html_erb___3831310028264182552_70339844987120'
app/controllers/lessons_controller.rb:20:in `show'

Request

Parameters:

{"id"=>"1"}

Show session dump

Show env dump
Response

Headers:

None

如果您需要更多信息,请告诉我。

4

2 回答 2

5

这个链接帮助了我:https ://github.com/sinatra/sinatra/issues/559#issuecomment-7748296

我用过<% text = tok.text.force_encoding 'UTF-8' %>,效果很好。

感谢@zed_0xff 让我走上了正确的道路。

于 2012-12-14T15:09:05.040 回答
1

试试这个解决方法

<% text = tok.text.encode('utf-8',:invalid => :replace, :undef => :replace) %>
<%= "#{text} [#{tok.start}..#{tok.end}]" %>
于 2012-12-14T14:45:35.620 回答