首页 > 解决方案 > 删除特殊字符前后的空格并将它们加入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']

起初我尝试使用它,但我认为正则表达式可以提供帮助

谢谢

标签: pythonregex

解决方案


是的,您可以使用正则表达式轻松解决此问题,而不是您当前的代码。

你可以使用这个正则表达式,

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

此正则表达式捕获一个空格,后跟字符集中的一个字符,后跟可选空格,并将其替换为它在第 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.

让我知道这是否适合您。


推荐阅读