[英]Sentence generator with words from lists using Python
因此,我嘗試學習python,並且編寫了這段代碼,該代碼應該從隨機單詞和隨機數的列表中生成句子,我已經從此代碼開始,但是不確定是否會起作用
這是我的代碼:
import random
num = random.randrange(0, 9)
drug = ['Advil', 'Synthroid', 'Crestor', 'Nexium', 'Vyvanse', 'Lyrica']
form = ['capsule', 'tablet', 'Powder', 'gel', 'liquid solution', 'Eye drops']
lines = []
for item in drug, form:
line = '- the patient was prescribed [' + num + '](dosage) [' + item.form + '](form) of [' + item.drug + '] for [' + num + 'days](Duration)
lines.append(line)
這是我期望的結果:
[the patient was prescribed [1](Dosage) [capsule](Form) of [Advil](Drug) for [5 days](Duration),
the patient was prescribed [2](Dosage) [Powder](Form) of [Nexium](Drug) for [6 days](Duration),
the patient was prescribed [5](Dosage) [luiquid solution](Form) of [Vyvanse](Drug) for [4 days](Duration),
...]
這就是你可以做到的
import random
## generate 6 random numbers
nums = [random.randrange(0, 9) for _ in range(6)]
days = nums = [random.randrange(0, 9) for _ in range(6)]
drugs = ['Advil', 'Synthroid', 'Crestor', 'Nexium', 'Vyvanse', 'Lyrica']
forms = ['capsule', 'tablet', 'Powder', 'gel', 'liquid solution', 'Eye drops']
lines = []
## zip will take one element from each array at one time
for num, drug, form, day in zip(nums, drugs, forms, days):
## this is string formatting syntax in python you put your local
## variable inside curly brackets
line = F"- the patient was prescribed {num} dosage {form} of {drug} for {day} days"
lines.append(line)
print(lines)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.