【问题标题】:How to read the second line in a document.txt and then make a loop that reads line +1 in this document如何读取 document.txt 中的第二行,然后循环读取此文档中的 +1 行
【发布时间】:2019-08-19 15:45:32
【问题描述】:

我的机器人从 document.txt 文件中逐一读取电子邮件,并在使用此电子邮件登录后,机器人输出我在另一个文件中的 cmets。

我已经达到了机器人阅读电子邮件的地步,但我希望特定帐户发表特定而不是重复评论。

所以我想到了从 cmets 文件中读取特定行的解决方案。

例如,帐户 1 读取并放入 cmets 文件的第 1 行。我想知道如何从 cmets 文件中读取第二行。

这是我一一阅读 cmets 时的代码部分,但我想阅读例如第二行或第三行!

file = 'comments.txt'
File.readlines(file).each do |line|
    comment = ["#{line}"] 
    comment.each { |val| 
        comment = ["#{val}"] 
}
end

【问题讨论】:

    标签: ruby watir


    【解决方案1】:

    File.readlines 返回数组。所以你可以做任何你想做的事

    lines = []
    
    File.readlines(path_to_file, chomp: true).each.with_index(1) do |line, line_number|
      lines << (line_number == 2 ? 'Special line' : line)
    end
    

    【讨论】:

      【解决方案2】:

      试试下面的。

      # set the line number to read
      line_number = 2 # <== Reading 2nd line
      comment = IO.readlines('comments.txt')[line_number-1]
      

      【讨论】:

      • 它显示以下错误:未定义的局部变量或方法`line_number'..可以给我一个例子吗?
      【解决方案3】:

      您的代码在每次迭代中都会覆盖注释变量。

      我会这样写你的代码:

      lines = File.readlines('comments.txt')
      lines.each do |line|
        # entire line
      end
      

      在循环中,你可以用一行代码做很多事情,不幸的是,我没有 100% 得到你想要做的事情(一条评论与多条评论,对于特定用户来说总是一样的,等等)我希望这无论如何都有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        • 2014-02-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2021-12-11
        相关资源
        最近更新 更多