[英]How to remove symbols from list elements in python
我有一个列表,其中包含各种内容,看起来与此类似:
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
我目前正在像这样迭代它:
def myFunction(exList)
result = []
yElement = exList[0]
for ch in yElement:
if ch in SYMBOLS: #I have a list of symbols saved globally in another area
exList.remove(ch)
result = exList
我已经尝试了其他几种方法来解决这个问题,但一无所获。 我的问题是如何遍历列表元素并删除所有符号,然后继续下一个列表元素? 任何帮助将不胜感激。
SYMBOLS = '{}()[].,:;+-*/&|<>=~'
我想最终得到一个列表,如:
['JM', 'the quick brown fox', 'word']
>>> SYMBOLS = '{}()[].,:;+-*/&|<>=~$1234567890'
>>> strings = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
>>> [item.translate(None, SYMBOLS).strip() for item in strings]
['JM', 'the quick brown fox', 'word']
如果您希望第一个字符串看起来像JM
,并且您还缺少$
字符,则还必须将数字添加到SYMBOLS
。
从文档:
S.translate(table [,deletechars]) -> 字符串
返回字符串 S 的副本,其中删除了可选参数 deletechars 中出现的所有字符,其余字符已通过给定的转换表映射,该转换表必须是长度为 256 或 None 的字符串。 如果 table 参数为 None,则不应用任何转换,并且该操作仅删除 deletechars 中的字符。
您也可以使用正则表达式来完成,但如果您只需要简单的替换,这种方式会更简洁。
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
SYMBOLS = '{}()[].,:;+-*/&|<>=~'
results = []
for element in exList:
temp = ""
for ch in element:
if ch not in SYMBOLS:
temp += ch
results.append(temp)
print results
您最初发布的代码的扩展:
SYMBOLS = '${}()[].,:;+-*/&|<>=~1234567890'
def myFunction(exList):
result = map(lambda Element: Element.translate(None, SYMBOLS).strip(), exList)
return result
exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
print myFunction(exList)
输出:
['JM', 'the quick brown fox', 'word']
如何使用 string.translate 方法并将标点符号列表传递给它? 这可能是最简单的方法。
>>> exList = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
>>> import string
>>> cleanList = []
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> for i in exList:
cleanList.append(i.translate(None,string.punctuation+string.digits))
>>> cleanList
['JM', 'the quick brown fox', 'word ']
>>>
字符串翻译可用于从字符串中删除字符,它的使用方式如下:
>>> k = "{}()hello$"
>>> k.translate(None,string.punctuation)
'hello'
SYMBOLS = '{}()[].,:;+-*/&|<>=~$1234567890'
strings = ['JM = {12, 23, 34, 45, 56}', 'the quick brown fox', 'word ($(,))']
[item.translate({ord(SYM): None for SYM in SYMBOLS} ).strip() for item in strings]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.