简体   繁体   English

如何使用python从文本中删除特定符号?

[英]How to remove specific symbols from a text using python?

I have a string like this: 我有一个像这样的字符串:

string = 'This is my text of 2013-02-11, & it contained characters like this! string ='这是我2013年2月11日的文本,其中包含这样的字符! (Exceptional)' (出色)”

These are the symbols I want to remove from my String. 这些是我想从字符串中删除的符号。

!, @, #, %, ^, &, *, (, ), _, +, =, `, /

What I have tried is: 我试过的是:

listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/']
exceptionals = set(chr(e) for e in listofsymbols)
string.translate(None,exceptionals)

The error is: 错误是:

an integer is required 需要一个整数

Please help me doing this! 请帮我这样做!

Try this 尝试这个

>>> my_str = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)'
>>> my_str.translate(None, '!@#%^&*()_+=`/')
This is my text of 2013-02-11,  it contained characters like this Exceptional

Also, please refrain from naming variables that are already built-in names or part of the standard library. 另外,请不要命名已经是内置名称或标准库一部分的变量。

How about this? 这个怎么样? I've also renamed string to s to avoid it getting mixed up with the built-in module string . 我还已将string重命名为s以避免它与内置模块string混淆。

>>> s = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)'
>>> listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/']
>>> print ''.join([i for i in s if i not in listofsymbols])
This is my text of 2013-02-11,  it contained characters like this Exceptional

Another proposal, easily expandable to more complex filter criteria or other input data type: 另一个建议,可以轻松扩展到更复杂的过滤条件或其他输入数据类型:

from itertools import ifilter

def isValid(c): return c not in "!@#%^&*()_+=`/"

print "".join(ifilter(isValid, my_string))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM