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

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

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

瀏覽:264日期: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 | 国产a级淫片 | 久久久一区二区三区四区 | 一级看片免费视频 | 可以看毛片的网站 | 国产成人av一区二区三区在线观看 | 老牛影视av一区二区在线观看 | 亚洲福利影院 | 精品久久免费 | 亚洲美女视频在线 | 国产专区一区 | 国产精品6 | 婷婷中文网 | 国产美女久久久久久 | 小香蕉av| 另类图片亚洲色图 | 91黄色免费视频 | 黄色免费一级 | 天天综合欧美 | 综合99 | 日本在线观看一区二区三区 | 少妇久久久久久久久久 | 日韩影视一区 | 成人免费看片视频 | 久久久久久久久爱 | 极品久久久久久久 | 国产成人黄色av | 日韩在线免费看 | 99久久婷婷国产综合精品草原 | 中文字幕8 | www.亚洲一区二区 | 可以免费观看的av | 亚洲免费观看视频 | 日韩精品视频在线免费观看 | 亚洲天堂网在线观看 | 欧美性色黄 | 超碰丝袜 | 中文字幕欧美在线 | 国产精品久久久久久久久久久久久久久久久 |