Python - 从列表中删除标点符号

Try*_*ard 2 python python-3.x

我需要从文本文件中删除punc.

文本文件是这样的

ffff,hhhh和tommorw回家,
你离开了吗?

我在尝试

PUNC =(",/;?& - ")

f = open('file.txt','r')

for line in f:
    strp=line.replace(punc,"")
    print(strp)
Run Code Online (Sandbox Code Playgroud)

我需要输出为:

ffff hhhh tommorw home

Have you from gone
Run Code Online (Sandbox Code Playgroud)

这是返回每一行,但punc仍然存在>可以使用一些帮助.谢谢

nne*_*neo 9

用于str.translate从字符串中删除字符.

在Python 2.x中:

# first arg is translation table, second arg is characters to delete
strp = line.translate(None, punc)
Run Code Online (Sandbox Code Playgroud)

在Python 3中:

# translation table maps code points to replacements, or None to delete
transtable = {ord(c): None for c in punc}
strp = line.translate(transtable)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用str.maketrans以构建transtable:

# first and second arg are matching translated values, third arg (optional) is the characters to delete
transtable = str.maketrans('', '', punc)
strp = line.translate(transtable)
Run Code Online (Sandbox Code Playgroud)