【问题标题】:How to replace a punctuation with a space in this code?如何在此代码中用空格替换标点符号?
【发布时间】:2019-05-24 18:13:02
【问题描述】:

我有这个代码:

 def remove_punctuation(self,text):
        exclude = set(string.punctuation)
        a=''.join(ch for ch in text if ch not in exclude)
        return ''.join(c for c in a if not ud.category(c).startswith('P'))

首先我想知道这是做什么的:

ch for ch in text if ch not in exclude

怎么可能写出这样的for循环?

其次,我想替换那些标点符号,让我们在这样的文本中说: “你好?我的朋友!”使用上面的代码有一个空格。我怎样才能更改该代码来做到这一点?

【问题讨论】:

  • “那些标点符号”是什么意思?
  • 您可以阅读list comprehensions 以了解ch for ch in text if ch not in exclude 行的作用。基本上:它会删除所有不在 exclude 中的字符
  • @Austin 我编辑了帖子
  • 这本质上不是一个列表理解(而是一个生成器)。尽管如此,阅读它会帮助您了解正在发生的事情。列表推导比使用join 的生成器推导更高效。

标签: python for-loop punctuation


【解决方案1】:

这段代码:

a = ''.join([ch for ch in text if ch not in exclude])

等价于

string_without_punctuation = ''
exclude = set(string.punctuation) # =set('!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~')
for character in text:
    if character not in exclude:
        string_without_punctuation += character

你可以简单地用空格替换标点符号:

string_without_punctuation = ''
exclude = set(string.punctuation) # =set('!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~')
for character in text:
    if character not in exclude:
        string_without_punctuation += character
    else:
        string_without_punctuation += ' '

【讨论】:

  • 此代码不会像我发布的代码那样删除 unicode 标点符号
  • 你可以把if character not in exclude:改成if character not in exclude and not ud.category(character).startswith('P'):
  • 还是没有解决
【解决方案2】:

我建议使用str.translate 而不是手动重建字符串。制作一个查找表,将字符映射到要替换的字符串。

trans = str.maketrans(dict.fromkeys(string.punctuation, ' '))

"hello_there?my_friend!".translate(trans)
# 'hello there my friend '

【讨论】:

  • 它是否也删除了 unicode 标点符号?因为我发布的上面的代码确实
  • @JohnSall 不,我一定错过了。 translate 仍然可以使用,但使用正则表达式可能会更成功。看到这个答案:stackoverflow.com/questions/11066400/…
猜你喜欢
  • 2016-04-23
  • 1970-01-01
  • 2018-03-21
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
相关资源
最近更新 更多