色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

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

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

瀏覽:146日期: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 編程
相關文章:
主站蜘蛛池模板: 日本黄色毛片 | 成年人色网站 | 在线观看一区 | 自拍网在线 | 精品在线视频观看 | 国产精品三级在线观看 | 亚洲欧美日韩综合在线一区二区三区 | 成 人 动漫在线观看网站网站 | 99精品国产成人一区二区 | 91久久国产综合精品女同国语 | 草草在线免费视频 | 韩国毛片 | 成人国产第一区在线观看 | 亚洲第一成年网 | 国产精品久久一区一区 | 国产aaa女人十八毛片 | 精品国产高清不卡毛片 | 在线观看国产 | 亚洲在线看 | 在线欧美视频 | 欧美成人手机在线 | 成年人免费观看的视频 | www.日本高清.com | 欧美一级毛级毛片 | 看a网站 | 粉嫩jk制服美女啪啪 | 精品一区二区影院在线 | 久久一日本道色综合久久m 久久伊人成人网 | 在线国产网站 | 国产高清在线精品一区a | 国产国产人免费视频成69堂 | 美美女下面被cao爽 美女131爽爽爽做爰中文视频 | a毛片免费全部播放毛 | 日韩中文字幕在线免费观看 | 中文无线乱码二三四区 | 欧美三级成人观看 | 亚洲欧洲国产视频 | 草草影院在线观看 | 亚洲成人黄色网址 | 91在线亚洲| 日韩精品一区二区三区免费观看 |