简体   繁体   English

Python字母重复替换Unicode字符串

[英]Python letters duplicates replace in Unicode string

I need to replace two mistyped letters in a string, for example "bbig". 我需要在字符串中替换两个输入错误的字母,例如“bbig”。 But it works only for Latin Letters, not for Cyrillic. 但它只适用于拉丁字母,而不适用于西里尔字母。 I am using Python version 2.6.6 under Centos Linux. 我在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')

The code above returns: 上面的代码返回:

  • ББООЛЛЬЬШШООЙЙ ББООЛЛЬЬШШООЙЙ
  • BIG

What did I do wrong? 我做错了什么? Thanks for your help. 谢谢你的帮助。

You are using byte strings. 您正在使用字节字符串。 This makes everything you use match and replace bytes. 这使得您使用的所有内容都匹配并替换字节。 That won't work if you want to match and replace letters. 如果你想匹配和替换字母,这将不起作用。

Use unicode strings instead: 改为使用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')

Note that this works fine for precomposed characters but will fall flat with characters composed using combining marks. 请注意,这适用于预先组合的字符,但使用组合标记组成的字符将会平滑。

It will also be disastrous if the user tries to type this very sentence (hint: check its second word). 如果用户试图输入这个句子(提示:检查它的第二个单词),那也将是灾难性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM