简体   繁体   中英

Getting Python to read the next line in a text file after user inputs Y to continue

I am a student and have been looking but not found an answer that makes sense to me yet so I apologise.

Basically I am creating a chatbot that will read out facts from a text file. I want the bot to read one line, then ask to continue. If Y, it reads out the next line until the end or the user says N.

So far it can read one line, then it just reads the same line over and over. I know there's other things wrong with it too but I'm just trying to get this part to work atm. I am self taught so sorry if this is bad.

Appreciate any input!

# Defining functions
def well_bot():
    print("Hi there, my name is Well Bot. ")
    print("My job is to tell people general facts about mental health and different types of mental illnesses. ")
    
    info = get_info()
    print(info)
    
    #this should only print if they want a fact
    getfact = print_facts()
    print(getfact)

    #var to read from illnesses text file to add later


def get_info():
    res = input("What can I teach you about today? \n[a] Facts \n[b] Types \n> ")

    if res == "a":
        print ("Okay. I will give you some general facts about mental health. ")
        with open('facts.txt') as facts:
            next_fact = facts.readline()
            print (next_fact)
            return continue_ask()
    
    elif res == "b":
        return "Okay, I can tell you about two different mental illnesses: \n[1] Depression \n[2] Bipolar Disorder \n> "
    else:
        print_message()
        return get_info()

def continue_ask():
    while True:
        if input("Want to know more? Enter Y to continue or N to finish: ") == "Y":
            with open('facts.txt') as facts:
                next_fact = facts.readline()
                print (next_fact)
                return continue_ask()
        else:
            print ("Okay, thanks, bye! ")
            break

def print_message():
    print("I'm sorry, I didn't quite get that. Can you choose again? ")
    return get_info()

#Call Bot
well_bot()

Open once and store line-by-line in an array

file = []   
with open('facts.txt') as facts:
    file = facts.read().split('\n')


line = 0
def continue_ask():
    global line
    while True: # not a fan of that would rather self call imo
        if input("Want to know more? Enter Y to continue or N to finish: ") == "Y":
            line+=1
            try:
                print(file[line])
            except IndexError:
                print("no more facts left :(")
                break
        else:
            print ("Okay, thanks, bye! ")
            break

This should do the trick

def gen_lines(filepath):
    """Lines Generator: Open the file and yield each line"""
    with open(filepath) as f:
        for line in f:
            yield line


def choose_argument():
    """Ask the user to choose an argument and return the right line generator."""
    argument = input("What can I teach you about today? \n[a] Facts \n[b] Types \n> ")
    if argument.lower() == "a":
        return gen_lines("facts.txt")
    elif argument.lower() == "b":
        return gen_lines("types.txt")
    else:
        print("I'm sorry, I don't know what you want me to do.")
        return choose_argument()


def asking_loop(line_generator):
    """Looping the lines asking the user at each step."""
    # Get the first line from the generator.
    print(next(line_generator))
    # Loop until the user says "no".
    while True:
        whant_more = input("Do you want to know more? \n[y] Yes \n[n] No \n> ")
        if whant_more.lower() == "y":
            print(next(line_generator))
            continue
        elif whant_more.lower() == "n":
            print("Okay, thanks, bye! ")
            break
        else:
            print("I'm sorry, I don't know what you want me to do.")
            continue


def main():
    """Main function."""
    print("Hi there, my name is Well Bot. ")
    print("My job is to tell people general facts about mental health and different types of mental illnesses. ")
    line_generator = choose_argument()
    asking_loop(line_generator)


if __name__ == "__main__":
    main()

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