字符串中规范化行结束符的最Pythonic方法是什么?
给定一个来源不明的文本字符串,我们该如何将它改写成一个已知的换行符格式呢?
我通常会这样做:
lines = text.splitlines()
text = '\n'.join(lines)
... 但这样做并不能处理那些“混合”的文本文件,这些文件的换行符完全混乱(没错,它们确实还存在!)。
编辑
我正在做的事情可以用一句话概括:
'\n'.join(text.splitlines())
... 但这并不是我想问的。
最后的行数应该保持不变,所以不能去掉空行。
测试案例
分割
'a\nb\n\nc\nd'
'a\r\nb\r\n\r\nc\r\nd'
'a\rb\r\rc\rd'
'a\rb\n\rc\rd'
'a\rb\r\nc\nd'
'a\nb\r\nc\rd'
.. 这些都应该最终得到5行。在混合的情况下,splitlines会认为'\r\n'是一个逻辑上的换行符,这样最后两个测试案例就会得到4行。
嗯,包含'\r\n'的混合上下文可以通过比较splitlines()和split('\n'),以及split('\r')的结果来检测...
3 个回答
0
除了 \r\n\
和 \n
这两种换行符,还有其他的换行方式吗?如果你不需要换行,直接把 \r\n
替换掉就可以了。
only_newlines = mixed.replace('\r\n','\n')
7
... 但是这并没有处理那些完全混乱的文本文件格式(是的,这种情况还是存在的!)
其实它应该能正常工作:
>>> s = 'hello world\nline 1\r\nline 2'
>>> s.splitlines()
['hello world', 'line 1', 'line 2']
>>> '\n'.join(s.splitlines())
'hello world\nline 1\nline 2'
你用的是什么版本的Python?
编辑:我还是不明白为什么splitlines()
对你不起作用:
>>> s = '''\
... First line, with LF\n\
... Second line, with CR\r\
... Third line, with CRLF\r\n\
... Two blank lines with LFs\n\
... \n\
... \n\
... Two blank lines with CRs\r\
... \r\
... \r\
... Two blank lines with CRLFs\r\n\
... \r\n\
... \r\n\
... Three blank lines with a jumble of things:\r\n\
... \r\
... \r\n\
... \n\
... End without a newline.'''
>>> s.splitlines()
['First line, with LF', 'Second line, with CR', 'Third line, with CRLF', 'Two blank lines with LFs', '', '', 'Two blank lines with CRs', '', '', 'Two blank lines with CRLFs', '', '', 'Three blank lines with a jumble of things:', '', '', '', 'End without a newline.']
>>> print '\n'.join(s.splitlines())
First line, with LF
Second line, with CR
Third line, with CRLF
Two blank lines with LFs
Two blank lines with CRs
Two blank lines with CRLFs
Three blank lines with a jumble of things:
End without a newline.
据我所知,splitlines()
并不会把列表分割两次或者其他什么的。
你能贴一个让你困扰的输入样本吗?
18
mixed.replace('\r\n', '\n').replace('\r', '\n')
应该处理所有可能的变体。