亚洲免费在线视频-亚洲啊v-久久免费精品视频-国产精品va-看片地址-成人在线视频网

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

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

瀏覽:173日期: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 編程
相關文章:
主站蜘蛛池模板: 成人亚洲国产综合精品91 | 一级片免费视频 | 国产4tube在线播放 | 亚洲韩国日本欧美一区二区三区 | 美女被拍拍拍拍拍拍拍拍 | 国产一级大片免费看 | 亚洲情a成黄在线观看动 | 亚欧成人中文字幕一区 | 日韩欧免费一区二区三区 | 精品看片 | 手机在线精品视频 | 国产精品一区二区三区久久 | 高h原耽肉汁动漫视频 | 亚洲成a人片在线观看中 | 手机看片日本 | 欧美一区二区三区不卡片 | 91精品视品在线播放 | 精品久久久久久无码中文字幕 | 亚洲午夜色 | 欧美成人性色xxxxx视频大 | 午夜私人影院免费体验区 | 69交性视频 | 久久久久久国产精品免费 | 亚洲国产欧美日韩 | 欧美国产高清欧美 | 亚洲精品在线视频 | 久久日本精品一区二区免费 | baoyu121永久免费网站 | 深爱五月开心网亚洲综合 | 亚洲国产精品看片在线观看 | 成人免费毛片一区二区三区 | 欧美成人短视频 | 美女被免费网站在线视频软件 | avtt天堂网 手机资源 | 女人aaaaa片一级一毛片 | 亚洲免费久久 | 香港激情黄三级在线视频 | 日韩免费精品一级毛片 | 国产日韩欧美精品 | 久久福利青草精品资源 | 在线免费观看欧美 |