将字符串拆分为单词和标点符号而不使用任何导入

2024-10-02 18:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我见过与我的问题类似的问题,但它们都使用正则表达式。我想做的是输入诸如“哇,这真的很有用!”并返回到“哇,这真的很有用!”的内容,所以我想从单词中分离标点符号。我试过这个,但根本不起作用:

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

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

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

Tags: in内容forinputif单词elsesentence
1条回答
网友
1楼 · 发布于 2024-10-02 18:28:10

你的问题不是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循环开始后的其余代码需要缩进。完成循环后,可以返回到与之前相同的缩进级别

相关问题 更多 >