我正在尝试删除标点符号,下面是codeimport字符串
FormEvents::POST_SUBMIT
当我使用strtext = "Professor Michael S. Hart is @ the originator of the Project Gutenberg-tm, concept // of a library of electronic works that could be freely shared with anyone. For thirty years, he produced and distributed Project Gutenberg-tm eBooks with only a loose network of volunteer support."
print(strtext.strip(string.punctuation))
print(strtext.translate(None, string.punctuation))
当我使用Traceback (most recent call last):
File "test.py", line 4, in <module>
print(strtext.translate(None, string.punctuation))
TypeError: translate() takes exactly one argument (2 given)
标点符号时,不会删除。
这可能是什么问题?
是的,我进行了搜索并在stackoverflow上遇到了几个问题,但没有解决我的问题。
答案 0 :(得分:2)
这适用于(在Python3中):
print(strtext.translate(str.maketrans('', '', string.punctuation)))
关于您的尝试:
strtext.strip(string.punctuation)
会尝试从string.punctuation
('!"#$%&\'()*+,-./:;<=>?@[\\]^_
{|}〜') from the beginning and end of
strtext`中删除每个字符。它不会删除字符串中的字符。
strtext.translate(None, string.punctuation)
:translate()
需要一个dict作为参数,你可以使用像上面这样的maketrans()构建。
答案 1 :(得分:1)
导入字符串
string.translate(strtext, None, string.punctuation)
OR
strtext.translate(None, string.punctuation)
string.translate(s, table[, deletechars])
如果table为None,则仅执行字符删除步骤。
<小时/> 注意仅在python2
上有效
答案 2 :(得分:0)
你正在使用python3 (最有可能)。
尝试:
trans_table = dict.fromkeys(map(ord, string.punctuation), None)
print(strtext.translate(trans_table))