【发布时间】: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