5

我使用代码从标点符号中删除一行文本:

line = line.rstrip("\n")
line = line.translate(None, string.punctuation)

问题是像doesn'tturn to这样的词,doesnt所以现在我只想删除词之间的标点符号,但似乎无法找到这样做的方法。我该怎么办?

编辑:我考虑过使用该strip()功能,但这只会对整个句子的左右尾随生效。

例如:

Isn't ., stackoverflow the - best ?

应该变成:

Isn't stackoverflow the best

而不是当前输出:

Isnt stackoverflow the best
4

2 回答 2

11

假设您将单词视为由空格分隔的字符组:

>>> from string import punctuation
>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(word.strip(punctuation) for word in line.split() 
             if word.strip(punctuation))
"Isn't stackoverflow the best"

或者

>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(filter(None, (word.strip(punctuation) for word in line.split())))
"Isn't stackoverflow the best"
于 2013-04-01T09:12:27.300 回答
-1
line = line.translate(None, string.punctuation.replace('\'', ''))

这是你想要的吗?

于 2013-04-01T09:28:17.017 回答