【问题标题】:Padding multiple character with space - python用空格填充多个字符 - python
【发布时间】:2016-01-27 12:38:55
【问题描述】:

perl 中,我可以用空格填充我的标点符号:

s/([،;؛¿!"\])}»›”؟%٪°±©®।॥…])/ $1 /g;` 

Python,我试过这个:

>>> p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…'
>>> text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
>>> for i in p:
...     text = text.replace(i, ' '+i+' ')
... 
>>> text
u'this, is a sentence with weird \xbb  symbols \u2026  appearing everywhere \xbf '
>>> print text
this, is a sentence with weird »  symbols …  appearing everywhere ¿ 

但是有没有办法使用某种占位符符号,例如$1 in perl 我可以在 python 中使用 1 个正则表达式做同样的事情吗?

【问题讨论】:

  • 如果您可以发布单独的问题而不是将您的问题合并为一个问题,则最好。这样,它可以帮助人们回答您的问题,也可以帮助其他人至少寻找您的一个问题。谢谢!
  • @kayess,在这种情况下,几乎是同一个问题;我认为问另一个问题会导致重复。尤其是当\p{Open_Punctuation} 有点类似于u""""'<(["""

标签: python regex perl tokenize substitution


【解决方案1】:

$1 的 Python 版本是 \1,但您应该使用正则表达式替换而不是简单的字符串替换:

import re

p = ur'([،;؛¿!"\])}»›”؟%٪°±©®।॥…])'
text = u"this, is a sentence with weird» symbols… appearing everywhere¿"

print re.sub(p, ur' \1 ', text)

输出:

this , is a sentence with weird »  symbols …  appearing everywhere ¿ 

【讨论】:

    【解决方案2】:

    您可以使用re.sub,将\1 用作占位符。

    >>> p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…'
    >>> text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
    >>> text = re.sub(u'([{}])'.format(p), r' \1 ', text)
    >>> print text
    this, is a sentence with weird »  symbols …  appearing everywhere ¿
    

    【讨论】:

      【解决方案3】:

      使用format函数,插入unicode字符串:

      p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…'
      text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
      for i in p:
          text = text.replace(i, u' {} '.format(i))
      
      print(text)
      

      输出

      this, is a sentence with weird »  symbols …  appearing everywhere ¿ 
      

      【讨论】:

      • OP 想要摆脱 for 循环。您的答案在语义上与原始答案没有什么不同,只是您的答案运行得更快。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2012-06-19
      相关资源
      最近更新 更多