开发者

Counting words in JSON file with Ruby

What is the best way to count words in a JSON file with Ruby?

The 开发者_运维技巧scan method will do the job but spends a lot of memory.


Try the block version of scan:

count = 0
json_string.scan(/\w+/) { count += 1 }

If you don't want to read the whole file into memory at once:

count = 0
File.new("test.json").each_line do |line|
  line.scan(/\w+/) { count += 1 }
end

This assumes of course that your JSON file is formatted (using prettify_json.rb, for instance.) It won't do much good if everything is on a single line, obviously.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜