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

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

問題描述

我寫了一個處理文本的文件就是把文本中所有的符號都替換掉,替換成空格。用的python中maketrans和translate。其中在使用對于ASCII編碼的文件時是正常的,但對于utf-8文件時,就報錯,提示maketrans中的參數(shù)不等長,但是明明是一樣長的啊:

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() 查看。然后關(guān)于字符串什么的問題,最好說明 python 的版本

maketrans 參數(shù)長度不相等

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 的運行結(jié)果

標簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 亚洲成人高清 | 女人张开腿给人桶免费视频 | 日本一级毛片中文字幕 | 欧美日韩一区二区三区免费不卡 | 成人欧美日韩 | 国产香蕉98碰碰久久人人 | 中文久草| 久久久久亚洲精品影视 | 性生i活一级一片 | 韩国一级a毛片 | 欧美做爰野外在线视频观看 | 久久免费看视频 | 午夜精品一区二区三区在线观看 | 中文字幕精品一区二区三区视频 | 51国产偷自视频区视频手机播器 | 久久一本色系列综合色 | 国产20岁美女一级毛片 | 亚洲精品不卡视频 | 久久成人性色生活片 | 国产精品96久久久久久久 | 两性色午夜视频免费国产 | 成人午夜兔费观看网站 | 日韩专区亚洲精品欧美专区 | 国产日产欧美精品一区二区三区 | 国产精品亲子乱子伦xxxx裸 | 久久99国产亚洲高清观看首页 | 国产高清毛片 | 国产精品成人免费视频 | 88精品视频 | 在线国产欧美 | 国产一区二区在线视频播放 | 亚洲成人网页 | 国产年成美女网站视频免费看 | 求欧美精品网址 | 精品免费久久久久久成人影院 | 一区二区在线看 | 国产成人小视频在线观看 | 日韩一级视频 | 男人在线网址 | 色播亚洲精品网站 亚洲第一 | 亚洲高清国产一区二区三区 |