首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从文件python3中删除多个元字符

如何从文件python3中删除多个元字符
EN

Stack Overflow用户
提问于 2018-06-20 19:23:01
回答 1查看 254关注 0票数 0

如何从文件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
EN

回答 1

Stack Overflow用户

发布于 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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50947074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档