【问题标题】:iteration over each word in array迭代数组中的每个单词
【发布时间】:2011-05-06 20:25:55
【问题描述】:

我有一个非常大的 .txt 文件,我想编写一个 ruby​​ 脚本来过滤一些数据。基本上我想遍历每一行,然后将行中的单个单词存储在一个数组中,然后对这些单词进行操作。但是我无法在数组中分别获取每个单词

tracker_file.each_line do|line|
arr = "#{line}"

我可以像这样得到整行,但是单个单词呢?

谢谢

【问题讨论】:

    标签: ruby file


    【解决方案1】:

    对字符串使用split 方法。

    irb(main):001:0> line = "one two three"
    => "one two three"
    irb(main):002:0> line.split
    => ["one", "two", "three"]
    

    所以你的例子是:

    tracker_file.each_line do |line|
      arr = line.split
      # ... do stuff with arr
    end
    

    【讨论】:

      【解决方案2】:
      tracker_file.each_line do |line|
        line.scan(/[\w']+/) do |word|
          ...
        end
      end
      

      如果不需要遍历行,可以直接遍历单词:

      tracker_file.read.scan(/[\w']+/) do |word|
          ...
      end
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        tracker_file.each_line do |line|
            arr = line.split
        # Then perform operations on the array
        end
        

        split 方法将基于分隔符(在本例中为空格)将字符串拆分为数组。

        【讨论】:

          【解决方案4】:

          如果您正在阅读用英文编写的内容,并且文本可能包含连字符、分号、空格、句点等,您可能会考虑使用正则表达式,例如:

          /[a-zA-Z]+(\-[a-zA-Z]+)*/
          

          改为提取单词。

          【讨论】:

            【解决方案5】:

            你不必使用IO#each_line,你也可以使用IO#each(separator_string)

            另一种选择是使用IO#gets

            while word = tracker_file.gets(/separator_regexp/)
              # use the word
            end
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-12-22
              • 1970-01-01
              • 2013-12-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多