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...
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)
就像@martineau建议你需要一个分隔符来分隔不同的段落。 这甚至可以是一个新行字符(\n),在您拥有它之后,您可以读取文件的所有内容并按定义的分隔符将其拆分。 这样就生成了一个元素列表,每个元素都是一个段落。 一些示例代码:
这种方法有一些缺点,比如读取所有的内容,如果文件很大,那么在故事发生的那一刻,你会用不需要的东西填满内存。在
看看你的文本示例,知道你将连续打印检索到的文本,一次读一行可能是更好的解决方案:
^{pr2}$显然,在需要的地方添加一些逻辑控制。在
你想要这个:
my_list = my_string.splitlines()
https://docs.python.org/3/library/stdtypes.html#str.splitlines相关问题 更多 >
编程相关推荐