簡體   English   中英

在Python中刪除開頭/結尾和內部多個空格,但不刪除制表符,換行符或返回字符

[英]Remove leading/ending and internal multiple spaces but NOT tabs, newlines, or return characters, in Python

Python刪除字符串中所有空白的問題的答案顯示了分別從Python字符串中刪除前導/結尾,重復和所有空格的單獨方法。 但是strip()刪除制表符和換行符,而lstrip()僅影響前導空格。 使用.join(sentence.split())的解決方案似乎也刪除了Unicode空格字符。

假設我有一個字符串,在這種情況下,是使用Scrapy從網站上抓取的,如下所示:

['\n                        \n                    ',
         '\n                        ',
         'Some text',
         ' and some more text\n',
  ' and on another a line some more text', '
                ']

當我在其他上下文中使用文本時,換行符會保留文本的格式,但是所有多余的空間都很麻煩。 如何在保留換行符(除了任何\\ r或\\ t字符,如果有的話)的同時刪除所有前導,結尾和重復的內部空格?

我想要的結果(在我加入各個字符串之后)將是:

['\n\n\nSome text and some more text\nand on another line some more text']

沒有提供示例代碼,因為到目前為止,我所嘗試的只是上面所引用頁面上的建議,該建議可以避免我得到的結果。

在那種情況下, str.strip()不會為您提供幫助(即使您使用" "作為參數,因為它不會刪除字符串中的空格,僅會在字符串的開頭/結尾,並且會刪除單個空格)在"and"之前也是如此。

而是使用正則表達式從字符串中刪除2個或更多空格:

l= ['\n                        \n                    ',
         '\n                        ',
         'Some text',
         ' and some more text\n',
  ' and on another a line some more text']

import re

result = "".join([re.sub("  +","",x) for x in l])

print(repr(result))

印刷品:

'\n\n\nSome text and some more text\n and on another a line some more text'

編輯:如果我們將正則表達式應用於每一行,則正如您所指出的,在某些情況下我們無法檢測到\\n 因此,另一種更復雜的解決方案是應用正則表達式之前連接字符串,然后應用更復雜的正則表達式(請注意,我更改了字符串測試列表以添加更多的極端情況):

l= ['\n                        \n                    ',
         '\n                        ',
         'Some text',
         ' and some more text \n',
  '\n and on another a line some more text ']

import re

result = re.sub("(^ |(?<=\n) |  +| (?=\n)| $)","","".join(l))

print(repr(result))

印刷品:

'\n\n\nSome text and some more text\n\nand on another a line some more text'

現在,正則表達式中有5種情況將被刪除:

  • 從一個空格開始
  • 換行符后的空格
  • 2個以上的空格
  • 空格后跟換行符
  • 一個空格結束

事后回顧:看起來(過去)很復雜。 這里畢竟一個非正則表達式的解決方案,提供了完全相同的結果(如果沒有的話之間的多個空格):

result = "\n".join([x.strip(" ") for x in "".join(l).split("\n")])
print(repr(result))

只需連接字符串,然后根據換行符進行拆分,將strip " "作為參數的strip帶應用於保留制表符,然后根據換行符再次連接。

re.sub(" +"," ",x.strip(" "))進行鏈接,以注意單詞之間可能存在的雙倍空格:

result = "\n".join([re.sub("  +"," ",x.strip(" ")) for x in "".join(l).split("\n")])

如果願意,您還可以按照內置的字符串操作來完成整個操作。

l = ['\n                        \n                    ',
     '\n                        ',
     'Some text',
     ' and some more text\n',
     ' and on another a      line some more text',
     '              ']


def remove_duplicate_spaces(l):
    words = [w for w in l.split(' ') if w != '']
    return ' '.join(words)

lines = ''.join(l).split('\n')
formatted_lines = map(remove_duplicate_spaces, lines)
u = "\n".join(formatted_lines)

print(repr(u))

'\n\n\nSome text and some more text\nand on another a line some more text'

您還可以將整個事情折疊成一個單一的行:

s = '\n'.join([' '.join([s for s in x.strip(' ').split(' ') if s!='']) for x in ''.join(l).split('\n')])

# OR

t = '\n'.join(map(lambda x: ' '.join(filter(lambda s: s!='', x.strip(' ').split(' '))), ''.join(l).split('\n')))

暫無
暫無

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

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