[英]Python - How to split a list into two separate lists dynamically
I am using Python-3 and I am reading a text file which can have multiple paragraphs separated by '\\n'. 我正在使用Python-3,正在读取一个文本文件,该文件可以包含多个用'\\ n'分隔的段落。 I want to split all those paragraphs into a separate list. 我想将所有这些段落分成一个单独的列表。 There can be n number of paragraphs in the input file. 输入文件中可以有n个段落。
So this split and output list creation should happen dynamically thereby allowing me to view a particular paragraph by just entering the paragraph number as list[2] or list[3], etc.... 因此,此拆分和输出列表的创建应动态进行,从而使我可以通过仅将段落编号输入为list [2]或list [3]等来查看特定段落。
So far I have tried the below process : 到目前为止,我已经尝试了以下过程:
input = open("input.txt", "r") #Reading the input file
lines = input.readlines() #Creating a List with separate sentences
str = '' #Declaring a empty string
for i in range(len(lines)):
if len(lines[i]) > 2: #If the length of a line is < 2, It means it can be a new paragraph
str += lines[i]
This method will not store paragraphs into a new list (as I am not sure how to do it). 此方法不会将段落存储到新列表中(因为我不确定该怎么做)。 It will just remove the line with '\\n' and stores all the input lines into str variable. 它将只删除带有“ \\ n”的行,并将所有输入行存储到str变量中。 When I tried to display the contents of str, it is showing the output as words. 当我尝试显示str的内容时,它将输出显示为单词。 But I need them as sentences. 但是我需要它们作为句子。
And my code should store all the sentences until first occurence of '\\n' into a separate list and so on. 而且我的代码应该将所有句子存储到第一次出现'\\ n'到单独的列表中,依此类推。
Any ideas on this ? 有什么想法吗?
UPDATE I found a way to print all the lines that are present until '\\n'. 更新我找到了一种打印直到'\\ n'为止存在的所有行的方法。 But when I try to store them into the list, it is getting stored as letters, not as whole sentences. 但是,当我尝试将它们存储到列表中时,它是作为字母而不是整个句子存储的。 Below is the code snippet for reference 以下是供参考的代码段
input = open("input.txt", "r")
lines = input.readlines()
input_ = []
for i in range(len(lines)):
if len(lines[i]) <= 2:
for j in range(i):
input_.append(lines[j]) #This line is storing as letters.
even "input_ += lines" is storing as letters, Not as sentences. 甚至“ input_ + =行”也存储为字母,而不是句子。
Any idea how to modify this code to get the desired output ? 任何想法如何修改此代码以获得所需的输出?
Don't forgot to do input.close()
, or the file won't save. 不要忘记做input.close()
,否则文件将不会保存。
Alternatively you can use with
. 或者您可以使用with
。
#Using "with" closes the file automatically, so you don't need to write file.close()
with open("input.txt","r") as file:
file_ = file.read().split("\n")
file_
is now a list with each paragraph as a separate item. 现在, file_
是一个列表,其中每个段落都作为单独的项。
It's as simple as 2 lines. 只需两行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.