Home > Software design >  Unable to findout vowel count using python
Unable to findout vowel count using python

Time:09-17

I am trying to find out ID numbers where the number of vowels in the body is an even number for the URL: https://jsonplaceholder.typicode.com/posts

My code is given below:

import json

import requests

   
url ='https://jsonplaceholder.typicode.com/posts'
content = requests.get(url).content

j = json.loads(content)
for each in j:

        print(each['id'],each['body'])

I am now able to print the body for each user ID but unable to find out the number of vowels in the body which is an even number. Need help

CodePudding user response:

You can count vowels with this code:

print(*map(each['body'].lower().count, "aeiou"))

whole code:

import json

import requests

   
url ='https://jsonplaceholder.typicode.com/posts'
content = requests.get(url).content

id_even = []
j = json.loads(content)
for each in j:
    cnt_vwl = 0
    for c in "aeiou":
        cnt_vwl  = each['body'].lower().count(c)
    if cnt_vwl%2==0:
        id_even.append(each['id'])
id_even

Output: (id that each['body'] have even vowels)

[1, 3, 4, 5, 6, 7, 10,...]

CodePudding user response:

Here is a solution using a list comprehension and re.sub to keep only the vowels:

import re

ids_even_vowels = [i['id']
                   for i in j if i['body']
                   if not len(re.sub('[^aeiouy]', '', i['body'], flags=re.I))%2==1
                  ]

output:

[1, 3, 4, 5, 6, 7, 10, 12, 15, 16, 18, 20, 22, 24, 27, 31, 32, 33, 34, 35, 40, 45, 46, 48, 49, 50, 53, 55, 56, 57, 58, 61, 63, 65, 66, 67, 68, 73, 76, 78, 82, 84, 90, 92, 95, 96, 97, 99]

how counting the vowels works:

>>> my_string = 'AbCDefGHI'

>>> re.sub('[^aeiouy]', '', my_string, flags=re.I)
'AeI'   # vowels only

>>> len(re.sub('[^aeiouy]', '', my_string, flags=re.I))
3       # number of vowels

>>> len(re.sub('[^aeiouy]', '', my_string, flags=re.I))%2
1       # remainder of division by 2: 1 is odd, 0 is even

>>> not len(re.sub('[^aeiouy]', '', my_string, flags=re.I))%2
False   # is it even?
  • Related