[英]Removing odd \n, \t, \r and space combinations from a given string in Python
我有一個長字符串,其中包含\\ n,\\ r,\\ t和單詞與其他字符之間的空格的各種組合。
我已經嘗試通過各種方式來使''.join(str.split())
失敗。
這里正確的Python方式是什么?
對於Python 3.x,解決方案會有所不同嗎?
例如 串:
ex_str = u'Word \n \t \r \n\n\n word2 word3 \r\r\r\r\nword4\n word5'
所需的輸出[新換行= \\ n]:
new_str = u'Word\nword2 word3\nword4\nword5'
使用組合str.splitlines()
並使用str.splitlines()
在所有空格上str.split()
:
'\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip()])
這分別對待每行,刪除空行,並在折疊每行的所有空格為單個空格。
如果輸入的是Python 3字符串,則相同的解決方案適用於兩個Python版本。
演示:
>>> ex_str = u'Word \n \t \r \n\n\n word2 word3 \r\r\r\r\nword4\n word5'
>>> '\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip(' ')])
u'Word\nword2 word3\nword4\nword5'
為了保存標簽,你需要剝離和拆分的只是空間,並篩選出空字符串:
'\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip()])
演示:
>>> '\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip(' ')])
u'Word\n\t\nword2 word3\nword4\nword5'
使用簡單的正則表達式:
import re
new_str = re.sub(r'[^\S\n]+', ' ', re.sub(r'\s*[\n\t\r]\s*', '\n', ex_str))
使用正則表達式:
>>> s
u'Word \n \t \r \n\n\n word2 word3 \r\r\r\r\nword4\t word5'
>>> re.sub(r'[\n\r\t ]{2,}| {2,}', lambda x: '\n' if x.group().strip(' ') else ' ', s)
u'Word\nword2 word3\nword4\nword5'
>>>
使用正則表達式的另一種解決方案是將制表符替換為空格u'word1\\t\\tword2'
,或者您是否真的也想在此處添加換行符?
import re
new_str = re.sub(r"[\n\ ]{2,}", "\n", re.sub(r"[\t\r\ ]+", " ", ex_str))
'\n'.join(str.split())
輸出:
u'Word\nword2\nword3\nword4\nword5'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.