python3.x - python 中的maketrans在utf-8文件中该怎么使用
问题描述
我写了一个处理文本的文件就是把文本中所有的符号都替换掉,替换成空格。用的python中maketrans和translate。其中在使用对于ASCII编码的文件时是正常的,但对于utf-8文件时,就报错,提示maketrans中的参数不等长,但是明明是一样长的啊:
File '/Users/lgq/Desktop/p3.py', line 10, in text_to_words
'abcdefghijklmnopqrstuvwxyz ')
ValueError: the first two maketrans arguments must have equal length
我查了一下说是maketrans在utf-8下不能用,那我在utf-8下该怎么替换掉字符呢,求各位大神指点。
def text_to_words(the_text): ''' Return a list of words with all punctuation removed,and all in lowercase. ''' my_substitutions = the_text.maketrans(# If you find any of these'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'#$%&()*+,-./:;<=>?@[]^_`{|}~’',# Replace them by these'abcdefghijklmnopqrstuvwxyz ') # Translate the text now. cleaned_text = the_text.translate(my_substitutions) wds = cleaned_text.split() return wdsdef get_words_in_book(filename): ''' Read a book from filename, and return a list of its words.''' f = open(filename, 'r', encoding = 'utf-8') content = f.read() f.close() wds = text_to_words(content) return wdsbook_words = get_words_in_book('alice.txt')print('There are {0} words in the book, the first 100 aren{1}'.format(len(book_words), book_words[:100]))
问题解答
回答1:首先 这两个字符串长度不相等, ' 是一个字符, 也是一个字符你可以用 len() 查看。然后关于字符串什么的问题,最好说明 python 的版本
maketrans 参数长度不相等
my_substitutions = the_text.maketrans(# If you find any of these'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'#$%&()*+,-./:;<=>?@[]^_`{|}~’',# Replace them by these'abcdefghijklmnopqrstuvwxyz ')
测试代码:
from string import translate, maketransdef text_to_words(the_text): ''' Return a list of words with all punctuation removed,and all in lowercase. ''' my_substitutions = maketrans(# If you find any of these'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'#$%&()*+,-./:;<=>?@[]^_`{|}~’',# Replace them by these'abcdefghijklmnopqrstuvwxyz ') # Translate the text now. cleaned_text = the_text.translate(my_substitutions) wds = cleaned_text.split() return wdstext_to_words(’ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'#$%&()*+,-./:;<=>?@[]^_`{|}~’测试’)
output
[’abcdefghijklmnopqrstuvwxyz’, ’xe6xb5x8bxe8xafx95’]
这是 python2 的运行结果
相关文章:
1. macos - mac下docker如何设置代理2. angular.js - ng-grid 和tabset一起用时,grid width默认特别小3. apache - 本地搭建wordpress权限问题4. 热切期待朱老师的回复,网页视频在线播放器插件配置错误5. docker 下面创建的IMAGE 他们的 ID 一样?这个是怎么回事????6. java - Spring Mvc全局异常处理器@ControllerAdvice不起作用?7. Whitelabel错误页面发生意外错误(类型=未找到,状态= 404)/WEB-INF/views/home.jsp8. javascript - web网页版app返回上一页按钮在ios设备失效怎么办?安卓上可以,代码如下,请大神帮助,万分感谢。9. Android下,rxJava+retrofit 并发上传文件和串行上传文件的效率为什么差不多?10. css3 - transition属性当鼠标一开的时候设置的时间不起作用
