【问题标题】:Parsing Text File in Ruby with "^z" Characters用“^z”字符在 Ruby 中解析文本文件
【发布时间】:2015-10-22 18:01:25
【问题描述】:

我有一组大型文本文件,其中包含大量信息且格式不一致。我不太关心大多数信息,但我正在尝试提取文件中包含的 ID。为此,我起草了一个相当简单的脚本(ID 为 3 位 - 7 位)。

puts("What's the name of the file you'd like to check? (don't include .txt)")

file_to_check = gets.chomp
file_to_write = file_to_check + "IDs" + ".txt"
file_to_check = file_to_check + ".txt"
output_text = ""
count_of_lines = 0

File.open(file_to_check, "r").each_line do |line|
    count_of_lines += 1
    if /.*\d{3}-\d{7}.*/ =~ line
        temp_case = line.match(/\d{3}-\d{7}/).to_s
        temp_case = temp_case + "\n"
        output_text = output_text + temp_case
    else
        # puts("this failed")
    end
end

File.open(file_to_write, "w") do |file|
    file.puts(output_text)
    file.puts(count_of_lines)
end

其中一个文件包含 VIM 显示为 ^Z 的字符,这似乎在脚本实际到达文件末尾之前杀死了脚本。

我可以做些什么让 Ruby 忽略这些字符并继续在文件中移动?

【问题讨论】:

  • 谢谢!我使用基于该线程的“rt”平面而不是“r”,它成功了。
  • /.*\d{3}-\d{7}.*/ 可以简化为/\d{3}-\d{7}/。也就是说,.* 不会使其更具限制性。匹配字符串1234-12345678,返回234-1234567。如果您不想匹配该字符串,可以将正则表达式更改为/\b\d{3}-\d{7}\b/\b 是“断字”。这意味着第一个匹配的数字必须在字符串的开头或前面有除数字、字母或下划线以外的字符。最后一个匹配的数字类似。

标签: ruby io


【解决方案1】:

根据 Mircea 的评论,答案是 here。我根据所选答案的其中一个 cmets 使用了“rt”。

【讨论】:

  • 这不是答案。它应该被删除。
猜你喜欢
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多