我試圖找出ID號碼,其中主體中的元音數是URL的偶數。https://jsonplaceholder.typicode.com/posts
我的代碼如下:
import json
import requests
url ='https://jsonplaceholder.typicode.com/posts'/span>
content = requests.get(url).content
j = json.load(content)
for each in j:
print(each['id'],each['body'] )
我現在能夠為每個用戶ID列印正文,但無法找出正文中的元音數,而這是一個偶數。需要幫助
uj5u.com熱心網友回復:
你可以用這個代碼計算元音:
print(*map(each['body'/span>]. lower().count, "aeiou"))
整個代碼:
import json
import requests
url ='https://jsonplaceholder.typicode.com/posts'/span>
content = requests.get(url).content
id_even = []
j = json.load(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
輸出。(id that each['body'] have even vowels)
[1, 3, 4, 5, 6, 7, 10, 。 ..]
uj5u.com熱心網友回復:
這里是一個使用串列理解和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' # 僅限元音。
>>> len(re.sub('[^aeiouy]', ', my_string, flags=re.I)
3 # 元音的數量>>> len(re. sub('[^aeiouy]', ', my_string, flags=re.I))%2
1 # 除以2的余數:1是奇數,0是偶數 # 除以2的余數:1是奇數,0是偶數>>> not len(re. sub('[^aeiouy]', '', my_string, flags=re.I))%2
False # is it even?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/308562.html
標籤:
上一篇:撰寫一個Python程式來測驗一個通過的字母是否是元音
下一篇:TiDB 學習筆記一(運維管理)
