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

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

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

瀏覽:118日期: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 編程
相關文章:
主站蜘蛛池模板: 国内精品一区二区三区东京 | 日韩午夜激情视频 | 欧美一区日韩精品 | 欧美 亚洲 一区 | 国产在线拍揄自揄拍视频 | 国产亚洲一欧美一区二区三区 | 日韩精品一区二区三区高清 | 国产成人一区二区三区视频免费 | 国产精品高清m3u8在线播放 | 50岁老女人毛片一级亚洲 | 青草香蕉精品视频在线观看 | 又黄又爽一线毛片免费观看 | 在线国产视频观看 | 国产毛片高清 | 日本黄色免费一级片 | 国产综合欧美日韩视频一区 | 成人在线免费 | 一级α一级α片免费观看网站 | 91粉色视频在线观看 | 国产91视频免费 | 特级淫片国产免费高清视频 | 成人在线激情网 | 亚洲精品tv久久久久久久久久 | 亚洲国产精品a在线 | 免费看三级黄色片 | 中文国产成人精品久久96 | 亚洲欧美日本韩国 | 色图在线观看 | 国产一级精品视频 | 1024 在线观看视频免费 | 97在线视频观看 | 亚洲欧美日韩精品久久奇米色影视 | 在线国产高清 | 香蕉视频在线观看www | 一级毛片视频 | 日本美女黄视频 | 亚洲精品在线观看91 | 久青草视频免费视频播放线路1 | 国产羞羞视频在线观看 | 片在线观看免费观看视频 | 91在线 | 欧美|