簡體   English   中英

標准化字符串中的行尾的最Python方式是什么?

[英]What's the most pythonic way of normalizing lineends in a string?

給定一個未知來源的文本字符串,如何最好地重寫它以具有已知的行尾約定?

我通常這樣做:

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行。 在混合上下文中,分割線假定'\\ r \\ n'是單個邏輯換行符,最后兩個測試用例導致4行。

嗯,可以通過比較splitlines()和split('\\ n')和/或split('\\ r')的結果來檢測包含'\\ r \\ n'的混合上下文...

mixed.replace('\r\n', '\n').replace('\r', '\n')

應該處理所有可能的變體。

...但是這不能處理完全混淆的約定的“混合”文本文件(是的,它們仍然存在!)

實際上,它應該可以正常工作:

>>> 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()不會兩次拆分列表。

您可以粘貼給您帶來麻煩的那種輸入示例嗎?

還有比\\r\\n\\\\n更多的驚喜嗎? 如果您不需要行,只需替換\\r\\n就足夠了。

only_newlines = mixed.replace('\r\n','\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM