-1

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.

S.cll
  • 123
  • 1
  • 1
  • 6
  • just trying to find a solution – S.cll Aug 01 '18 at 09:22
  • What have you tried so far? StackOverflow is not a free code writing service (that's why you're getting downvoted); you need to show a bit more effort. What libraries are you using? What documentation are you referencing? Do you have a partial solution? An incorrect result? An error message? Anything at all? – Tom Lord Aug 01 '18 at 14:01
  • Ok. I just come up with a partial solution . I will put it on the origin post. – S.cll Aug 02 '18 at 03:51
  • At a glance... `tokens.select { |t| t.part_of_speech.tag.to_s == 'NOUN' }.count`? Only the first 4 lines of your code are needed; the rest can be deleted. (And I assume you're using the `sentences` for something else, further down?) – Tom Lord Aug 02 '18 at 09:22
  • It works. Thanks a lot. And yes, I need sentences for something else :D – S.cll Aug 03 '18 at 07:29

1 Answers1

0

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.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • thanks. and the [ruby-style-guide](https://github.com/rubocop-hq/ruby-style-guide#no-for-loops) is really helpful. – S.cll Aug 06 '18 at 06:47