我需要从文本文件中删除punc.
文本文件是这样的
ffff,hhhh和tommorw回家,
你离开了吗?
我在尝试
PUNC =(",/;?& - ")
f = open('file.txt','r')
Run Code Online (Sandbox Code Playgroud)for line in f: strp=line.replace(punc,"") print(strp)
我需要输出为:
ffff hhhh tommorw home
Run Code Online (Sandbox Code Playgroud)Have you from gone
这是返回每一行,但punc仍然存在>可以使用一些帮助.谢谢
用于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)
| 归档时间: |
|
| 查看次数: |
12984 次 |
| 最近记录: |