ruby-on-railsrubycountgoogle-cloud-nl

How to count the number of noun appeared in a paragraph with Google's NL api using ruby?


Trying to count the number of noun appeared in a paragraph with Google's NL api using ruby.

Been looking up the document, couldn't find how to do this.

Work out a solution last night

text = 'xxxxxxxxxx'
response = language.analyze_syntax content: text, type: :PLAIN_TEXT

sentences = response.sentences
tokens    = response.tokens
x= tokens.count

a = Array.new(x-1)

for i in 1..x
    a[i-1] = tokens[i-1].part_of_speech.tag.to_s
end
for i in 1..x
    if a[i-1] == 'NOUN' 

    num= num+1
    end
end

still wondering if there exist something like (tokens.noun.count ?) in the nl api https://cloud.google.com/natural-language/docs/analyzing-syntax#language-syntax-string-ruby.


Solution

  • Building on your example, you could count the number of NOUNs like so:

    text = 'xxxxxxxxxx'
    response = language.analyze_syntax content: text, type: :PLAIN_TEXT
    
    tokens = response.tokens
    
    tokens.count { |t| t.part_of_speech.tag.to_s == 'NOUN' }
    

    Note that in ruby, it is very common style to use iterators like this, rather than defining temporary variables and using for loops. (In fact, you should almost never find a need to use for loops in ruby!)

    This clean, concise syntax is one of the biggest appeals of the ruby language. Very often, you can obtain a desired result in one line of code like that rather than all of this temporary array and index counter declarations.