简体   繁体   中英

TypeError: expected a character buffer object When execute a translate function

It's for removing punctuation of a str .

tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
                      if unicodedata.category(unichr(i)).startswith('P'))
def remove_punctuation(text):
    return text.translate(tbl)

remove_punctuation(',')

But it shows the error message when i run the code:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/untitled2/is_include.py", line 22, in <module>
    remove_punctuation('')
  File "C:/Users/user/PycharmProjects/untitled2/is_include.py", line 20, in remove_punctuation
    return text.translate(tbl)
TypeError: expected a character buffer object

text.translate() is expecting a string. Make sure you convert tbl to a string first.

def remove_punctuation(text):
    return text.translate(str(tbl))

UPDATE:

Or, as Sven Marnach mentioned in the comment reply, you can use a unicode-translate instead.

remove_punctuation(u',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM