我有以下字符串:
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“之间。这是因为他们之间已经有了一个空间。
这个问题也会出现在:with= "Hello. (hi)“中。产出如下:
" Hello . ( hi ) "请注意开括号前的两个空格。
我需要的输出只有一个空格之间的任何标点符号和单词,除了上面提到的5个标点符号,这是不分隔的词。我怎么才能解决这个问题?或者,是否有更好的方法使用regex来完成此操作?
提前谢谢。
发布于 2015-01-07 03:27:00
看来re可以帮你..。
>>> import re
>>> re.sub(r"([\w/'+$\s-]+|[^\w/'+$\s-]+)\s*", r"\1 ", 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 ! "和
>>> re.sub(r"([\w/'+$\s-]+|[^\w/'+$\s-]+)\s*", r"\1 ", "Hello. (hi)")
'Hello . ( hi ) '如果尾随空间有问题,.rtrim(theresult, ' ')应该为您修复它:-)
发布于 2015-01-07 03:26:35
我可以试试这个方法吗?
>>> import string
>>> 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!"
>>> ls = []
>>> for x in input:
... if x in string.punctuation:
... ls.append(' %s' % x)
... else:
... ls.append(x)
...
>>> ''.join(ls)
"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 !"
>>>发布于 2015-01-07 03:28:20
由于缺乏声誉而无法发表评论,但在这里
在句子中的第一个感叹号和单词"Do“之间
看起来有两个空格,因为之间已经有一个空格了!然后去做
好了!做
所以,如果标点符号后面已经有一个空格,不要再放一个空格。
此外,这里还有一个类似的问题:python regex inserting a space between punctuation and letters
所以也许可以考虑使用re
https://stackoverflow.com/questions/27810884
复制相似问题