【问题标题】:Get a letter index inside a text node? [closed]在文本节点内获取字母索引? [关闭]
【发布时间】:2014-01-14 19:54:06
【问题描述】:
<span class="word">fab
  <span class="green">u</span>lous
</span>

这段 HTML 只是一个带有绿色字母“u”的单词“fabulous”。我需要找出这个词中绿色字母的索引。

CSS .word 选择整个单词,.green 可以分辨出字母“u”是绿色的。但我实际上不知道哪个“你”是绿色的。

如何获得绿色字母位置?

【问题讨论】:

  • 你到底想要什么?
  • 使用css('.word').children 然后遍历所有的孩子并查找green span...
  • 我不知道 children 方法的用法。它只是在这里完成工作。非常感谢您的精彩回答!这正是我这个问题所需要的。

标签: css ruby nokogiri


【解决方案1】:

我想你想在一个单词中找到绿色字母的位置,所以我可以这样做:

require 'nokogiri'

str1 = '<span class="word">fab<span class="green">u</span>lous</span>'
str2 = '<span class="word">fabulo<span class="green">u</span>s</span>'

def get_green str
  doc = Nokogiri::HTML(str)
  sh = 0
  doc.css('.word').children.each do |c|
    sh += c.text.length
    if c['class'] == 'green'
      break
    end
  end
  sh - 1
end

p get_green(str1)
p get_green(str2)

输出是:

# => 3
# => 6

绿色字母的出现和位置(如果有的话):

require 'nokogiri'

str1 = '<span class="word">fab<span class="green">u</span>lous</span>'
str2 = '<span class="word">fabulo<span class="green">u</span>s</span>'
str3 = '<span class="word">fabulo<span class="red">u</span>s</span>'

def get_green str
  doc = Nokogiri::HTML(str)
  char = doc.css('.word .green').text
  return [-1, -1] if char == ""
  occurance = 0
  position = 0
  doc.css('.word').children.each do |el|
    break if el['class'] == 'green'
    position += el.text.length
    occurance += el.text.chars.select{|ch| ch == char}.length
  end
  [occurance + 1, position]
end

p get_green(str1)
p get_green(str2)
p get_green(str3)

输出:

# => [1, 3]
# => [2, 6]
# => [-1, -1]

【讨论】:

  • 为什么是 3,我认为应该是 1 ? 1 表示第一个u。不是6..它就像2ndu.
  • @ArupRakshit ,只是认为它应该返回绿色字母的position...在我看来index == position ;)
  • +1.... 无论如何.. 好方法。我在想什么,我无法编码。 :(
  • @ArupRakshit ,根据您的情况更新。
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
相关资源
最近更新 更多