国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

python3.x - python 中的maketrans在utf-8文件中該怎么使用

瀏覽:127日期:2022-07-05 10:59:36

問題描述

我寫了一個處理文本的文件就是把文本中所有的符號都替換掉,替換成空格。用的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 的運行結果

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 不卡一级毛片免费高清 | 精品国产一区二区三区www | 国产日韩视频在线观看 | 欧美曰韩一区二区三区 | 久久久精品久久视频只有精品 | 看一级毛片国产一级毛片 | 九九综合九九 | 欧美三级网站在线观看 | 国产精品夜色视频一区二区 | 国产精品久久久久久久免费 | 亚洲国产激情一区二区三区 | 综合亚洲精品一区二区三区 | 怡红院在线观看在线视频 | 亚洲国产精品综合久久 | 精品欧美日韩一区二区三区 | 久久久日本久久久久123 | 在线成人免费观看国产精品 | 亚洲视频手机在线观看 | 国产五区 | 色婷婷激婷婷深爱五月老司机 | 精品九九久久 | 精品视频一区在线观看 | 美女网站视频黄色 | 免费一级肉体全黄毛片高清 | 一区二区三区亚洲视频 | 日本成人中文字幕 | www.久久久 | 亚洲一区二区精品视频 | 性猛交毛片| 亚洲黄a| 免费一级做a爰片性色毛片 免费一极毛片 | 激情欧美日韩一区二区 | 2022男人天堂| 亚洲精品一区亚洲精品 | 国产高清在线精品一区二区三区 | 欧美成人全部费免网站 | 黄网址在线看 | a级毛片毛片免费观看久潮喷 | 久久色视频在线观看 | 精品国产v | 久久tv免费国产高清 |