Issue
The following code adapted from a website for removing punctuations from words.
import string
filename = 'some_file.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
# split the text into words
words = text.split()
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in words]
print(stripped[:100])
The error is "TypeError: maketrans() takes exactly 2 arguments (3 given)"
.
I read the Python documentation that says the options for having 1, 2 or 3 arguments of maketrans(). The docs.python.org says: "If there is a third argument, it must be a string, whose characters will be mapped to None in the result".
I'm using Python 2. Any idea to clear the error?
Solution
I think you are confusing the python3.1 docs(where in the "If there is a third argument, it...... " statement is mentioned.) with Python2. As per python2 documentation - https://docs.python.org/2/library/string.html, it cannot have 3 parameters.
But if you want to achieve the functionality of having a 3rd parameter (to map a set of characters to None), you can do it by adding the string to translate
,
stripped = [w.translate(table, string.punctuation) for w in words]
Answered By - Sivakumar Natarajan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.