【问题标题】:Save twitter search result to JSON file将推特搜索结果保存到 JSON 文件
【发布时间】:2013-04-12 17:07:12
【问题描述】:

我正在使用 twitter ruby​​ gem 来获取 twitter 搜索结果。 Github 的示例代码从搜索结果中提取信息。我想知道如何将搜索结果(我认为是 JSON)保存到单独的 JSON 文件中。
以下是部分示例代码:

results = @search.perform("$aaa", 1000)
aFile = File.new("data.txt", "w")
results.map do |status|
myStr="#{status.from_user}: #{status.text}  #{status.created_at}"
aFile.write(myStr)
aFile.write("\n")
end

有没有办法将所有搜索结果保存到单独的 JSON 文件中,而不是将字符串写入文件?
提前致谢。

【问题讨论】:

  • 专业提示:使用File.open with a block 代替File.new 并手动关闭。这使得文件的关闭具有确定性和异常安全性。
  • JSON 只是数据格式化的一种方式。最终,它只是一根长长的绳子。您可以将数据保存到文件中,就像将其他文本保存到文件中一样。您无需使用任何特殊的文件扩展名保存它。

标签: ruby twitter


【解决方案1】:

如果你想保存到一个文件中,你需要做的就是打开文件,写入它,然后关闭它:

File.open("myFileName.txt", "a") do |mFile|
    mFile.syswrite("Your content here")
    mFile.close
end

当您使用open 时,如果文件不存在,您将创建该文件。

需要注意的一点是,打开文件有不同的方法,这些方法将决定程序写入的位置。 "a" 表示它会将您写入文件的所有内容附加到当前内容的末尾。

以下是一些选项:

r   Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+  Read-write mode. The file pointer will be at the beginning of the file.
w   Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+  Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a   Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+  Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

因此,在您的情况下,您需要提取要保存的数据,然后将其写入文件,如我所示。您还可以通过以下方式指定文件路径:

File.open("/the/path/to/yourfile/myFileName.txt", "a") do |mFile|
    mFile.syswrite("Your content here")
    mFile.close
end

需要注意的另一件事是open 不创建目录,因此您需要自己创建目录,或者您可以使用您的程序来创建目录。这是一个有助于文件输入/输出的链接:

http://www.tutorialspoint.com/ruby/ruby_input_output.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多