无法使用python查找元音计数

2024-09-29 01:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出ID号,其中正文中的元音数是URL的偶数:https://jsonplaceholder.typicode.com/posts

我的代码如下:

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'])

我现在可以打印每个用户ID的正文,但无法找到正文中的元音数,这是一个偶数。需要帮助吗


Tags: httpsimportcomidjsonurlcontentrequests
2条回答

您可以使用以下代码计算元音:

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

全部代码:

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

输出:(每个['body']都有偶数元音的id)

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

下面是一个使用列表理解和re.sub只保留元音的解决方案:

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
                  ]

输出:

[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]

如何计算元音:

>>> 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?

相关问题 更多 >