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

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

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

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

問題描述

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

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下該怎么替換掉字符呢,求各位大神指點(diǎn)。

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:

首先 這兩個(gè)字符串長(zhǎng)度不相等, ' 是一個(gè)字符, 也是一個(gè)字符你可以用 len() 查看。然后關(guān)于字符串什么的問題,最好說明 python 的版本

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

my_substitutions = the_text.maketrans(# If you find any of these'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!'#$%&()*+,-./:;<=>?@[]^_`{|}~’',# Replace them by these'abcdefghijklmnopqrstuvwxyz ')

測(cè)試代碼:

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!'#$%&()*+,-./:;<=>?@[]^_`{|}~’測(cè)試’)

output

[’abcdefghijklmnopqrstuvwxyz’, ’xe6xb5x8bxe8xafx95’]

這是 python2 的運(yùn)行結(jié)果

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 国产不卡网 | 91精品麻豆 | 精品视频国产 | 一级毛片在线免费观看 | 毛片亚洲毛片亚洲毛片 | 亚洲精品区 | 黄色片的网址 | 1024在线视频精品免费 | 亚洲图欧美日韩色综合图 | 日本高清免费不卡视频 | 亚洲专区一区 | 日韩欧免费一区二区三区 | 一区二区三区欧美 | 99久久精品费精品国产一区二 | 狠狠色欧美亚洲狠狠色五 | 日韩免费小视频 | 无夜精品久久久久久 | 成人午夜在线观看国产 | 尤物在线免费视频 | 无遮挡1000部拍拍拍免费 | 91国语精品自产拍在线观看性色 | 免费碰碰碰视频在线看 | 免费在线一级片 | 日本一级特黄aa大片 | 成年女人在线观看 | 国产青草视频在线观看 | 一级黄色录像播放 | 成人毛片18女人毛片免费视频未 | 日韩高清一区二区 | 曰曰碰天天碰国产 | 在线黄色.com | 在线欧美v日韩v国产精品v | 国产日韩欧美综合在线 | 全免费a级毛片免费看视频免 | 无码一区二区三区视频 | 免费福利视频在线观看 | 免费国产在线观看 | 韩国特黄色免费 | 国产丝袜第一页 | 亚洲精品视频免费看 | 99热只有精品一区二区 |