我正在尝试使用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
如果您需要更多信息,请告知我们。
答案 0 :(得分:4)
此链接帮助了我:https://github.com/sinatra/sinatra/issues/559#issuecomment-7748296
我使用<% text = tok.text.force_encoding 'UTF-8' %>
并且它有效。
感谢@ zed_0xff让我走上了正确的道路。
答案 1 :(得分:1)
尝试此解决方法
<% text = tok.text.encode('utf-8',:invalid => :replace, :undef => :replace) %>
<%= "#{text} [#{tok.start}..#{tok.end}]" %>