如何从文件python3中删除多个元字符同样,如果我想要删除双引号("
)、单引号('
)、加运算符(+
)、连字符(-
)、等号(=
)和逗号(,
)。
例如,对于双引号,我们可以这样做。
In [1]: import re
In [2]: re.sub(r"\"", "", '"remove all "double quotes" from text"')
Out[2]: 'remove all double quotes from text'
In [3]: re.sub(r"(^\"|\"$)", "", '"remove all "only surrounding quotes" from text"')
Out[3]: 'remove all "only surrounding quotes" from text'
让我们有一个类似下面的例子,我们在一个文件中有数千行这样的代码行,我们必须将其应用于相同的文件中:
adding new entry "cn=hdl-binsun+ipHostNumber=192.1698.232.92,ou=hosts,ou=corp,ou=services,o=hdl.com"
在模拟上面的例子时,我看到了下面的代码,它可以正常工作:
# replacer.py
import re
f = open('file.txt', mode='rt', encoding='utf-8')
for line in f:
new_str = re.sub(r'[+=",]', ' ', line)
print(new_str)
#new_str = re.sub(r'[-()\"#/@;:<>{}`+=~|.!?,%$]', ' ', line)
我得到了如下所需的输出
$ python replacer.py
adding new entry cn hdl-binsun ipHostNumber 192.168.232.92 ou hosts ou corp ou services o hdl.com
发布于 2018-06-20 19:36:59
只需使用替换函数man
您甚至不需要使用re
a = "remove all \"double quotes\" from text".replace("\"", "")
或者我们开始吧
def replacer(string, sth_to_remove):
return string.replace(sth_to_remove, "")
a = replacer(a, "\"")
您可以使用类似这样的列表
not_needed = ['+', '-', '\"']
def replacer(string, sth_to_remove):
if type(sth_to_remove) == list:
for i in sth_to_remove:
string = string.replace(i, "")
else:
string = string.replace(sth_to_remove, "")
return string
a = replacer(a, not_needed)
https://stackoverflow.com/questions/50947074
复制相似问题