【问题标题】:Strip special characters from string, retain, alphabets, numbers and punctuation marks [duplicate]从字符串、保留、字母、数字和标点符号中去除特殊字符[重复]
【发布时间】:2014-03-22 22:55:40
【问题描述】:

我正在尝试从所有特殊字符中清除字符串并保留其他所有内容,包括标点符号。

mystring = "Q18. On a scale from 0 to 10 where 0 means ‘not at all interested' and 10 means ‘very interested', how interested are you in helping to address problems that affect poor people in poor countries?"

到目前为止我的努力:

newlabel = re.sub('[^A-Za-z0-9]+', ' ', newstring)

输出:

Q18 On a scale from 0 to 10 where 0 means not at all interested and 10 means very interested how interested are you in helping to address problems that affect poor people in poor countries 

如何在我目前拥有的正则表达式中保留标点符号或有更好的解决方案?

【问题讨论】:

  • 你真的有very interested'之前的那个unicode字符吗?
  • 是的。不知道为什么或如何,但它在那里,我想摆脱它:)

标签: python regex string


【解决方案1】:

解决了,

print (newstring.decode('unicode_escape').encode('ascii','ignore'))

输出:

Q18. On a scale from 0 to 10 where 0 means not at all interested' and 10 means very interested', how interested are you in helping to address problems that affect poor people in poor countries?

【讨论】:

  • 您是否参考了其他东西来提出该解决方案?
  • 一旦你说它们是“unicodes”,我就快速搜索并在这里找到了答案:bit.ly/1nSSmjY
  • 太棒了。我将此问题标记为该问题的重复。对以后的读者会有帮助。
【解决方案2】:

如果您需要更改的只是保留点而不是将其添加到正则表达式将解决该问题。

re.sub('[^A-Za-z0-9\.]+', ' ', mystring)

【讨论】:

    【解决方案3】:

    只需在正则表达式中的每个标点符号前添加反斜杠.....

    【讨论】:

      猜你喜欢
      • 2016-02-20
      • 1970-01-01
      • 2022-01-22
      • 2020-11-19
      • 1970-01-01
      • 2011-08-16
      • 2019-07-31
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多