【问题标题】:python - How to remove punctuation in between wordspython - 如何删除单词之间的标点符号
【发布时间】:2013-04-01 09:08:11
【问题描述】:

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

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

【问题讨论】:

  • 我认为您需要更正式地解释您的确切要求,并提供一些具体的“之前和之后”示例。

标签: python


【解决方案1】:

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

>>> 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"

【讨论】:

    【解决方案2】:
    line = line.translate(None, string.punctuation.replace('\'', ''))
    

    这是你想要的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多