简体   繁体   中英

How to read from text file into array paragraph by paragraph?

Making a text based game and want to read from the story text file via paragraph rather than printing a certain amount of characters?

You wake up from a dazed slumber to find yourself in a deep dank cave with moonlight casting upon the entrance...

You see a figure approaching towards you... Drawing nearer you hear him speak...

my_list = my_string.splitlines()my_list = my_string.splitlines() https://docs.python.org/3/library/stdtypes.html#str.splitlines

Like @martineau suggested you need a delimiter for separate different paragraphs. This can even be a new line character (\\n) and after you have it you read all content of the file and split it by the defined delimiter. Doing so you generate a list of elements with each one being a paragraph. Some example code:

delimiter = "\n"
with open("paragraphs.txt", "r") as paragraphs_file:
    all_content = paragraphs_file.read() #reading all the content in one step
    #using the string methods we split it
    paragraphs = all_content.split(delimiter)

This approach has some drawbacks like the fact that read all the content and if the file is big you fill the memory with thing that you don't need now, at the moment of the story.

Looking at your text example and knowing that you will continuously print the retrieved text, reading one line a time could be a better solution:

with open("paragraphs.txt", "r") as paragraphs_file:
   for paragraph in paragraphs_file: #one line until the end of file
       if paragraph != "\n":
          print(paragraph)

Obviously add some logic control where you need it.

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