簡體   English   中英

刪除特殊字符前后的空白並加入python

[英]Remove White space before and after a special character and join them python

My_string =  My Awesome Company billing @ example . com Contractor Invoice # 000015 Acme Projects - Taxable Product Contractor Invoice Summary Account Information Don Test don @ example . com Contractor Invoice Date : 10 / 26 / 2016 Amount Due $ 21 .


Desired_string = My Awesome Company billing@example.com Contractor Invoice#000015 Acme Projects-Taxable Product Contractor Invoice Summary Account Information Don Test don@example.com Contractor Invoice Date:10/26/2016 Amount Due$21.

簡單來說,我需要刪除特殊字符前后的空格。 您還可以分享一個很好的資源來學習正則表達式嗎

with open('sentence.txt') as txtfile:
string = str(txtfile.read())
list_of_str = string.split()
new_list = []
for d in range(len(list_of_str)):
    if not (list_of_str[d].isalpha() or list_of_str[d].isalnum()):
       print(list_of_str[d-1], list_of_str[d:])
       new_list.append(str(list_of_str[d-1]) + str(list_of_str[d]) + str(list_of_str[d+1]))
    else:
        new_list.append(list_of_str[d])
print(new_list)

Output: ['OnlineMyAwesome', 'Awesome', 'Company', 'billing', 'billing@example', 'example', 'example.com', 'com', 'Contractor', 'Invoice', 'Invoice#000015', '000015', 'Acme', 'Projects', 'Projects-Taxable', 'Taxable', 'Product', 'Contractor', 'Invoice', 'Summary', 'Account', 'Information', 'Don', 'Test', 'don', 'don@example', 'example', 'example.com', 'com', 'Contractor', 'Invoice', 'Date', 'Date:10', '10', '10/26', '26', '26/2016', '2016', 'Amount', 'Due', 'Due$21', '21']

起初我嘗試使用它,但我認為正則表達式可以提供幫助

謝謝

是的,您可以使用正則表達式輕松地解決此問題,而不是使用當前代碼。

您可以使用此正則表達式,

([@.#$\\/:-]) ? (空格后跟具有特殊字符的字符集,后跟一個可選空格。您可以根據需要在該字符集中添加更多字符。)

此正則表達式捕獲一個空格,其后是字符集中的一個字符,后跟可選的空格,並用在組1中捕獲的字符替換它。

演示

示例python代碼,

import re
s = 'My Awesome Company billing @ example . com Contractor Invoice # 000015 Acme Projects - Taxable Product Contractor Invoice Summary Account Information Don Test don @ example . com Contractor Invoice Date : 10 / 26 / 2016 Amount Due $ 21 .'
s = re.sub(' ([@.#$\/:-]) ?',r'\1', s)
print(s)

提供以下輸出,

My Awesome Company billing@example.com Contractor Invoice#000015 Acme Projects-Taxable Product Contractor Invoice Summary Account Information Don Test don@example.com Contractor Invoice Date:10/26/2016 Amount Due$21.

讓我知道這是否適合您。

暫無
暫無

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

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