亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

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

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

瀏覽:151日期: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 編程
相關文章:
主站蜘蛛池模板: 国产精品每日在线观看男人的天堂 | 欧美黄区 | 精品国产成人在线 | 日韩毛片一级 | 精品国产一区二区三区久久 | 偷窥第一页 | 国产伦理久久精品久久久久 | 欧美精品久久久久久久免费观看 | 一级日本大片免费观看视频 | 国产一区二区成人 | 亚洲欧美国产视频 | 国产欧美日韩看片片在线人成 | 欧美成人伊人久久综合网 | 男女午夜爱爱久久无遮挡 | 1024cao社区榴地址一地址二 | 午夜成年人网站 | 中文字幕日韩在线一区国内 | 久久婷婷五综合一区二区 | 日韩一区二区视频在线观看 | 日韩乱淫 | julia一区二区中文字幕 | 特级深夜a级毛片免费观看 特极毛片 | 青草免费免费观看视频在线 | 劲爆欧美色欧美 | 亚洲成人mv | 色婷婷综合和线在线 | 一区二区三区视频在线 | 色综合网站国产麻豆 | 国产成人精品日本亚洲11 | 久久久精品久久久久久 | 成年网站在线观看视频 | 免费一看一级毛片全播放 | 99久久亚洲国产高清观看 | 一级做a爰片性色毛片黄书 一级做a爰片性色毛片新版的 | 国产美女无遮挡免费网站 | 亚洲日本色图 | 欧美a级v片在线观看一区 | 国产伦理自拍 | 国产欧美另类久久精品91 | 欧美桃色 | 日韩国产欧美一区二区三区 |