简体   繁体   中英

Sentence generator with words from lists using Python

So I'm trying to learn python, and I have written this code that's supposed to generate sentences from lists of random words and random numbers, I've started with this code but I'm not sure if it's gonna work

Here is my code:

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)

This is the results I'm expecting :

[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),
...]

This is how you can do it

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM