[英]python3: How to convert a string with Unicode encoding to a string of letters
[英]Python letters duplicates replace in Unicode string
我需要在字符串中替換兩個輸入錯誤的字母,例如“bbig”。 但它只適用於拉丁字母,而不適用於西里爾字母。 我在Centos Linux下使用Python 2.6.6版。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
def reg(item):
item = re.sub(r'([A-ZА-ЯЁЄЇІ])\1', r'\1', item, re.U)
#this work only with latin too
#item = re.sub(r'(.)\1', r'\1', item, re.U)
return item
print reg('ББООЛЛЬЬШШООЙЙ')
print reg('BBIIGG')
上面的代碼返回:
我做錯了什么? 謝謝你的幫助。
您正在使用字節字符串。 這使得您使用的所有內容都匹配並替換字節。 如果你想匹配和替換字母,這將不起作用。
改為使用unicode字符串:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
def reg(item):
item = re.sub(ur'([A-ZА-ЯЁЄЇІ])\1', r'\1', item, re.U)
#this work only with latin too
#item = re.sub(r'(.)\1', r'\1', item, re.U)
return item
print reg(u'ББООЛЛЬЬШШООЙЙ')
print reg(u'BBIIGG')
請注意,這適用於預先組合的字符,但使用組合標記組成的字符將會平滑。
如果用戶試圖輸入這個句子(提示:檢查它的第二個單詞),那也將是災難性的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.