如何从文本文件逐段读入数组?

2024-06-07 06:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

制作一个基于文本的游戏,想通过段落阅读故事文本文件而不是打印一定数量的字符?在

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...

Tags: tofrom文本you游戏数量字符段落
2条回答

就像@martineau建议你需要一个分隔符来分隔不同的段落。 这甚至可以是一个新行字符(\n),在您拥有它之后,您可以读取文件的所有内容并按定义的分隔符将其拆分。 这样就生成了一个元素列表,每个元素都是一个段落。 一些示例代码:

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)

这种方法有一些缺点,比如读取所有的内容,如果文件很大,那么在故事发生的那一刻,你会用不需要的东西填满内存。在

看看你的文本示例,知道你将连续打印检索到的文本,一次读一行可能是更好的解决方案:

^{pr2}$

显然,在需要的地方添加一些逻辑控制。在

你想要这个:my_list = my_string.splitlines()https://docs.python.org/3/library/stdtypes.html#str.splitlines

相关问题 更多 >