简体   繁体   English

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

[英]splitting lines into lines then adding all to a long list

i have some text that is split like so:我有一些像这样拆分的文本:

line 1 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

line 2 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

this goes on for a while as you can see.如您所见,这种情况持续了一段时间。 the paragraphs or groupings of lines are split by "\\n," how can i get all the paragraphs into one list with no smaller lists inside for ex:段落或行分组由“\\n”分割,我如何将所有段落放入一个列表中,其中没有较小的列表,例如:

list = ["hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph. hey I'm a paragraph.", "etc etc..."]

Assuming your text is in a file named file.txt , and that the \\n is a string and not an escape character, then you can do this by simply:假设您的文本位于名为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)

Is this what you are looking for?这是你想要的? Splitting the string into a list on the \\n?将字符串拆分为 \\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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM