将行拆分为行,然后将所有行添加到长列表中

问题描述 投票:0回答:2

我有一些像这样分割的文本:

第1行

hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph.\n, hey I'm a new paragraph. hey I'm a new paragraph. hey I'm a new paragraph.\n, hey im the third paragraph. hey im the third paragraph. hey im the third paragraph.\n

第2行

hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph.\n, hey I'm a new paragraph. hey I'm a new paragraph. hey I'm a new paragraph.\n, hey im the third paragraph. hey im the third paragraph. hey im the third paragraph.\n

如您所见,这会持续一段时间。行的段落或分组以“ \ n”分隔我怎样才能将所有段落放入一个列表,而里面没有更小的列表,例如:

list = ["hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph.", "etc etc..."]
python python-3.x list
2个回答
1
投票

假设您的文本在名为file.txt的文件中,并且\n是字符串而不是转义字符,那么您可以通过以下简单操作即可:

full_list = []

file = open('file.txt', 'r')

for line in file.readlines():
    full_list += [x.rstrip('\\n') for x in line.split('\\n,')]

file.close()
print(full_list)

0
投票

这是您要寻找的吗?将字符串拆分为\ n?

上的列表
string = '''hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph.\n, hey I'm a new paragraph. hey I'm a new paragraph. hey I'm a new paragraph.\n, hey im the third paragraph. hey im the third paragraph. hey im the third paragraph.\n'''
string_list = string.split('\n')
print(string_list)
© www.soinside.com 2019 - 2024. All rights reserved.