繁体   English   中英

如何删除单词之间的标点符号

[英]python - How to remove punctuation in between words

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

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

问题是,像话doesn't转向doesnt所以现在我只想字之间去除标点符号,但似乎无法找出一种方法来做到这一点。 我该怎么办呢?

编辑:我想过使用strip()函数,但这只会影响整个句子的左右拖尾。

例如:

Isn't ., stackoverflow the - best ?

应该成为:

Isn't stackoverflow the best

而不是当前的输出:

Isnt stackoverflow the best

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

>>> 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"
line = line.translate(None, string.punctuation.replace('\'', ''))

这是你想要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM