Python 将行拆分为行,然后将所有行添加到一个长列表中
我有一些像这样拆分的文本: 第1行Python 将行拆分为行,然后将所有行添加到一个长列表中,python,python-3.x,list,Python,Python 3.x,List,我有一些像这样拆分的文本: 第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
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..."]
这就是你要找的吗?正在将字符串拆分为列表中的\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)
假设您的文本位于名为
file.txt
的文件中,并且\n
是一个字符串而不是转义字符,则只需执行以下操作即可:
full_list=[]
file=open('file.txt','r')
对于文件.readlines()中的行:
完整列表+=[x.rstrip('\\n'),用于行中的x.split('\\n')]
file.close()文件
打印(完整列表)
第1行和第2行是单独定义的字符串还是列表?您指的是第1行
和第2行
…这些行在文件中吗?如果是这样的话,不是也用新行分隔吗?第1行是文本文件中的第一行第1行,第2行是stringscan您不就是这样做的吗full\u list=line1.split('\n')+line2.split('\n')
?您提供的数据给我的感觉是:逐行读取文件,将原始行输入csv,然后再次以文本形式读取csv…让我试试看,这很有魅力,但在我将“\n”放入列表后,有没有办法去掉它?很高兴提供帮助~~^_^