开发者

Counting words in JSON file with Ruby

开发者 https://www.devze.com 2023-03-31 09:26 出处:网络
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:

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

精彩评论

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