python3.x - python 中的maketrans在utf-8文件中該怎么使用
問題描述
我寫了一個(gè)處理文本的文件就是把文本中所有的符號都替換掉,替換成空格。用的python中maketrans和translate。其中在使用對于ASCII編碼的文件時(shí)是正常的,但對于utf-8文件時(shí),就報(bào)錯(cuò),提示maketrans中的參數(shù)不等長,但是明明是一樣長的?。?/p>
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下該怎么替換掉字符呢,求各位大神指點(diǎn)。
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:首先 這兩個(gè)字符串長度不相等, ' 是一個(gè)字符, 也是一個(gè)字符你可以用 len() 查看。然后關(guān)于字符串什么的問題,最好說明 python 的版本
maketrans 參數(shù)長度不相等
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 的運(yùn)行結(jié)果
相關(guān)文章:
1. windows誤人子弟啊2. php傳對應(yīng)的id值為什么傳不了啊有木有大神會的看我下方截圖3. 如何用筆記本上的apache做微信開發(fā)的服務(wù)器4. python - linux 下用wsgifunc 運(yùn)行web.py該如何修改代碼5. 關(guān)于mysql聯(lián)合查詢一對多的顯示結(jié)果問題6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 冒昧問一下,我這php代碼哪里出錯(cuò)了???8. mysql優(yōu)化 - MySQL如何為配置表建立索引?9. MySQL主鍵沖突時(shí)的更新操作和替換操作在功能上有什么差別(如圖)10. 數(shù)據(jù)庫 - Mysql的存儲過程真的是個(gè)坑!求助下面的存儲過程哪里錯(cuò)啦,實(shí)在是找不到哪里的問題了。
