Julia中的生成器表达式

时间:2014-07-27 11:03:35

标签: julia

我试图在Julia中实现Generator表达式,但是我遇到了一个我不知道如何修复的错误。

julia> using JSON

julia> path = "test.txt"

julia> JSON.parse(readline(open(path)))
Dict{String,Any} with 16 entries:
  "nk" => 1
  "cy" => "Danvers"
  "c"  => "US"
  "hh" => "1.usa.gov"
  "r"  => "http://www.facebook.com/l/7AQEFzjSi/1.usa.gov/wfLQtf"
  "a"  => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like …
  "h"  => "wfLQtf"
  "t"  => 1331923247
  "g"  => "A6qOVH"
  "tz" => "America/New_York"
  "ll" => {42.576698,-70.954903}
  "l"  => "orofrog"
  "hc" => 1331822918
  "gr" => "MA"
  "u"  => "http://www.ncbi.nlm.nih.gov/pubmed/22415991"
  "al" => "en-US,en;q=0.8"

julia> record = [JSON.parse(line) for line in eachline(open(path))]
ERROR: no method length(EachLine)
in anonymous at no file

2 个答案:

答案 0 :(得分:1)

您不能将列表推导用于长度不是先验已知的对象。我认为你需要一个while循环。

我也不确定您是否可以将JSON解析与面向行的输入一起使用,因为JSON边界可能跨越行边界。

答案 1 :(得分:1)

如果文件不是太大,可以使用readlines而不是eachline,因为它返回一个数组,而不是迭代器(并且数组有一个长度方法,可以用于理解)

我最喜欢的是您在评论中描述的那个:

using JSON
records = Dict{String,Any}[]
open(path,"r") do f
    for line in eachline(f)
        push!(records, JSON.parse(line))
    end
end