首页 > 解决方案 > 在不使用任何导入的情况下将字符串拆分为单词和标点符号

问题描述

我见过与我的问题类似的问题,但他们都使用了正则表达式。我想做的是接受诸如“哇,这真的很有帮助!”之类的输入。并返回“哇,这真的很有帮助!”所以我想将标点符号与单词分开。我已经尝试过这个,但它根本不起作用:

sentence = input()
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\]^`{|}~"
    for punc in sentence :

    if punc in punctuation :
        outputpunc = " %s" % punc
    else :

      outputpunc = character
    separatedPunctuation += outputpunc
print separatedPunctuation.split()

标签: pythonstringpunctuation

解决方案


你的问题不是 100% 清楚的,如果你想在一个标点符号后有第二个空格,如果两个出现一个接一个。

但是假设你对两个空格没问题,代码可能看起来像这样:

sentence_in = "Wow,this was really helpful!"
sentence_out = ""
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\]^`{|}~"

for character in sentence_in:

    if character in punctuation:
        sentence_out += " %s " % character
    else:
        sentence_out += character

print(sentence_out)

您的代码的问题在于它没有正确缩进,这在 Python 中很重要,因为它用于指示代码块。例如参见:

for punc in sentence :

if punc in punctuation :
    outputpunc = " %s" % punc
else :

    outputpunc = character

应该看起来像这样:

for punc in sentence :
    if punc in punctuation :
        outputpunc = " %s" % punc
    else :
        outputpunc = character

如您所见,for循环开始后的其余代码需要缩进。完成循环后,您可以返回到与以前相同的缩进级别。


推荐阅读