【问题标题】:How do I replace punctuation in a string in Python?如何在 Python 中替换字符串中的标点符号?
【发布时间】:2012-09-08 09:28:30
【问题描述】:

我想替换(而不是删除)Python中字符串中的所有标点符号“”。

下面的味道有什么有效的吗?

text = text.translate(string.maketrans("",""), string.punctuation)

【问题讨论】:

标签: python string replace


【解决方案1】:

来自Best way to strip punctuation from a string in Python的修改解决方案

import string
import re

regex = re.compile('[%s]' % re.escape(string.punctuation))
out = regex.sub(' ', "This is, fortunately. A Test! string")
# out = 'This is  fortunately  A Test  string'

【讨论】:

  • 你将如何保留撇号,例如在单词 don't 中?我不想去掉撇号,所以我只剩下不要了。
  • 您可以从 string.punctuation 中删除撇号(这又是一个包含所有标点符号的字符串)。 string.punctuation.replace("'", "") 导致 ` '!"#$%&()*+,-./:;?@[\]^_{|}~'
【解决方案2】:

此答案适用于 Python 2,仅适用于 ASCII 字符串:

字符串模块包含两个可以帮助您的东西:标点符号列表和“maketrans”函数。以下是您可以如何使用它们:

import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)

【讨论】:

【解决方案3】:

替换为''?

将所有;翻译成''和删除所有;有什么区别?

这里是删除所有;

s = 'dsda;;dsd;sad'
table = string.maketrans('','')
string.translate(s, table, ';')

你可以用翻译来代替。

【讨论】:

    【解决方案4】:

    以我的具体方式,我从标点符号列表中删除了“+”和“&”:

    all_punctuations = string.punctuation
    selected_punctuations = re.sub(r'(\&|\+)', "", all_punctuations)
    print selected_punctuations
    
    str = "he+llo* ithis& place% if you * here @@"
    punctuation_regex = re.compile('[%s]' % re.escape(selected_punctuations))
    punc_free = punctuation_regex.sub("", str)
    print punc_free
    

    结果:he+llo ithis& place if you here

    【讨论】:

      【解决方案5】:

      此解决方法适用于 python 3:

      import string
      ex_str = 'SFDF-OIU .df  !hello.dfasf  sad - - d-f - sd'
      #because len(string.punctuation) = 32
      table = str.maketrans(string.punctuation,' '*32) 
      res = ex_str.translate(table)
      
      # res = 'SFDF OIU  df   hello dfasf  sad     d f   sd' 
      

      【讨论】:

        【解决方案6】:

        有一个更强大的解决方案,它依赖于正则表达式排除而不是通过大量标点符号列表包含。

        import re
        print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
        #Output - 'This is fortunately A Test string'
        

        正则表达式捕获不是字母数字或空白字符的任何内容

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-15
          • 2015-10-14
          • 2014-07-31
          相关资源
          最近更新 更多