午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

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

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

瀏覽:276日期: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 編程
相關文章:
主站蜘蛛池模板: 噜噜色av | 黄色av网站在线观看 | 亚洲品质自拍 | 伊人成人在线视频 | 成年人不懂如何谈恋爱免费观看 | 中文字幕h | 黄色影院在线观看 | 福利在线小视频 | 精品久久久久久久久久 | 美女天堂网 | 亚洲第四页 | 国产成人99久久亚洲综合精品 | 日韩一级精品 | 欧美国产三级 | 在线视频日本 | 中文字幕天堂av | 黄色在线免费播放 | 草久视频在线观看 | 精品国产一区在线观看 | 影音先锋国产在线 | 国产成人精品一区二区 | 成年人在线观看网站 | 免费在线一级片 | 国产黄色av网站 | 久久久久久久999 | 日韩视频在线免费观看 | 天天插天天| 日本中文字幕视频 | 在线观看wwww | 欧美日韩高清一区二区三区 | 国产一区二区精品在线 | 久久久久久久久艹 | 三年中国中文在线观看免费播放 | 99热这里精品 | 欧美永久免费 | 欧美一级做a爰片免费视频 天堂久久精品 | 天天舔天天射 | 久久久精品视频在线观看 | 午夜在线视频 | 看片在线| 成人一区二区视频 |