如何使用Nokogiri提取具有两个单词长度的文本的ID元素

时间:2016-10-06 01:23:13

标签: ruby xml nokogiri

我有一个XML文件如下:

<w:p w14:paraId="646BED8B" w14:textId="30F19BEA" w:rsidR="00CA7979" w:rsidRDefault="00197F7D">
    <w:r>
        <w:t xml:space="preserve">This </w:t>
    </w:r>
    <w:r w:rsidR="00656E17">
        <w:t xml:space="preserve">first sentence </w:t>
    </w:r>
    <w:ins w:author="Mitchell Gould" w:date="2016-10-04T16:15:00Z" w:id="0">
        <w:r w:rsidR="00E24CA3">
            <w:t>is</w:t>
        </w:r>
    </w:ins>
    <w:del w:author="Mitchell Gould" w:date="2016-10-04T16:15:00Z" w:id="1">
        <w:r w:rsidDel="00E24CA3" w:rsidR="00656E17">
            <w:delText>was</w:delText>
        </w:r>
    </w:del>
    <w:r>
        <w:t xml:space="preserve">for checking the verb usage errors.  I will</w:t>
    </w:r>
    <w:ins w:author="Mitchell Gould" w:date="2016-10-04T16:18:00Z" w:id="2">
        <w:r w:rsidR="00BF77BA">
            <w:t xml:space="preserve">write</w:t>
        </w:r>
    </w:ins>
    <w:del w:author="Mitchell Gould" w:date="2016-10-04T16:18:00Z" w:id="3">
        <w:r w:rsidDel="00BF77BA">
            <w:delText xml:space="preserve">make</w:delText>
        </w:r>
    </w:del>
    <w:r>
        <w:t xml:space="preserve">some </w:t>
    </w:r>
    <w:r w:rsidR="00BF77BA">
        <w:t xml:space="preserve"/>
    </w:r>
    <w:r>
        <w:t>changes</w:t>
    </w:r>
    <w:r>
        <w:t xml:space="preserve">to the verbs and check it if the verbs </w:t>
    </w:r>
    <w:ins w:author="Mitchell Gould" w:date="2016-10-04T16:15:00Z" w:id="4">
        <w:r w:rsidR="00E24CA3">
            <w:t>are</w:t>
        </w:r>
    </w:ins>
    <w:del w:author="Mitchell Gould" w:date="2016-10-04T16:15:00Z" w:id="5">
        <w:r w:rsidDel="00E24CA3">
            <w:delText>is</w:delText>
        </w:r>
    </w:del>
    <w:r>
        <w:t xml:space="preserve">fixed.</w:t>
    </w:r>
</w:p>

我有一系列动词:

@verbs = ["is", "will", "write", "are", "should", "be", "will", "add", "see", "adding", "is", "should", "be", "inserted", "will", "delete", "view", "deleting", "works", "should", "be", "deleted", "tests", "adding", "should", "be", "was", "will", "make", "is", "should", "be", "will", "adding", "should", "be", "inserted", "will", "delete", "remove", "see", "deleting", "works", "working", "should", "be", "deleted", "test", "adding", "should", "be"]

我可以使用w:id获取所有元素,如下所示:

@elements = @file.xpath('//*[@w:id]')

但是,我想要做的只是获取文件中与以下内容匹配的元素:

  1. 文字不超过2个字
  2. 其中一个词包含在我的@verbs数组中。
  3. 我可以用Nokogiri这样做,如果是这样的话?

1 个答案:

答案 0 :(得分:1)

最简单的方法是混合使用Ruby:

@file.xpath('//*[@w:id]').select { |node|
  words = node.text.split
  words.length <= 2 && words.any? { |word| @verbs.include?(word) }
}

我刚刚想到,如果你要检查多个单词,那么将@verbs转换为集合会让你更开心:

require 'set'
@verbset = Set.new(@verbs)

然后检查@verbset.include?(word),因为它比测试数组中的成员资格要快得多。

相关问题