【问题标题】:How to convert an iterative str.replace() with str.translate()? - python如何用 str.translate() 转换迭代 str.replace()? - Python
【发布时间】:2013-10-25 17:18:03
【问题描述】:

我的任务的目的是在标点符号前后添加空格。目前我一直在使用迭代str.replace() 将每个标点符号p 替换为" "+p+" "如何使用str.translate() 实现相同的输出,我可以传入两个列表或字典

inlist = string.punctuation
outlist = [" "+p+" " for p in string.punctuation]
inoutdict = {p:" "+p+" " for p in string.punctuation}

假设我所有的标点符号都在string.punctuation 中。目前,我正在这样做:

from string import punctuation as punct
def punct_tokenize(text):
  for ch in text:
    if ch in deupunct:
      text = text.replace(ch, " "+ch+" ")
  return " ".join(text.split())

sent = "This's a foo-bar sentences with many, many punctuation."
print punct_tokenize(sent)

而且这个迭代 str.replace() 耗时太长,str.translate() 会更快吗?

【问题讨论】:

    标签: python string replace translate punctuation


    【解决方案1】:

    translate 的 dict 形式仅适用于 unicode:

    >>> import string
    >>> inoutdict = {ord(p):unicode(" "+p+" ") for p in string.punctuation}
    >>> unicode("foo,,,bar!!1").translate(inoutdict)
    u'foo ,  ,  , bar !  ! 1'
    

    另一种选择是使用正则表达式:

    >>> import re
    >>> rx = '[%s]' % re.escape(string.punctuation)
    >>> re.sub(rx, r" \g<0> ", "foo,,,bar!!1")
    'foo ,  ,  , bar !  ! 1'
    

    像往常一样,向我们展示更大的图景以获得更好的答案,例如你为什么这样做?输入来自哪里?等等......

    【讨论】:

    • \g&lt;0&gt; 是什么意思?
    • @alvas:这是引用“零组”的一种奇特(但唯一)方式 - 找到了整个子字符串。
    • 感谢解决方案,翻译和正则表达式解决了句子中标点符号前后添加空格的问题。我有" ".join(spaced_punct_text.split()) 来解决多个空格输出=)
    • 这两种解决方案的运行速度都比迭代的str.replace() 快很多 =)
    猜你喜欢
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多