【发布时间】:2015-03-04 20:11:56
【问题描述】:
我有以下字符串:
input = "I love programming with Python-3.3! Do you? It's great... I give it a 10/10. It's free-to-use, no $$$ involved!"
除“/”、“'”、“-”、“+”和“$”外,所有标点符号都应与单词分开。
所以输出应该是:
"I love programming with Python-3 . 3 ! Do you ? It's great . . . I give it a 10/10. It's free-to-use , no $$$ involved !"
我使用了以下代码:
for x in string.punctuation:
if x == "/":
continue
if x == "'":
continue
if x == "-":
continue
if x == "+":
continue
if x == "$":
continue
input = input.replace(x," %s " % x)
我得到以下输出:
I love programming with Python-3 . 3 ! Do you ? It's great . . . I give it a 10/10 . It's free-to-use , no $$$ involved !
它有效,但问题是它有时会在标点符号和单词之间留下两个空格,例如句子中的第一个感叹号和单词“Do”之间。这是因为它们之间已经有了空间。
这个问题也会发生在:input = "Hello. (hi)"。输出将是:
" Hello . ( hi ) "
注意左括号前的两个空格。
我需要在任何标点和单词之间只有一个空格的输出,除了上面提到的 5 个标点,它们没有与单词分开。我怎样才能解决这个问题?或者,有没有更好的方法使用正则表达式来做到这一点?
提前致谢。
【问题讨论】: