python - 在不使用任何导入的情况下将字符串拆分为单词和标点符号
问题描述
我见过与我的问题类似的问题,但他们都使用了正则表达式。我想做的是接受诸如“哇,这真的很有帮助!”之类的输入。并返回“哇,这真的很有帮助!”所以我想将标点符号与单词分开。我已经尝试过这个,但它根本不起作用:
sentence = input()
punctuation = "!\"#$%&'()*+,-./:;<=>?@[\]^`{|}~"
for punc in sentence :
if punc in punctuation :
outputpunc = " %s" % punc
else :
outputpunc = character
separatedPunctuation += outputpunc
print separatedPunctuation.split()
解决方案
你的问题不是 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循环开始后的其余代码需要缩进。完成循环后,您可以返回到与以前相同的缩进级别。
推荐阅读
- ruby - Ruby fork 进程时如何检测或记录(ubuntu 14.04)?
- java - Android自定义DialogFragment问题
- excel-formula - 如何在excel中组合多个COUNTIF公式
- excel - 在 Vlookup 公式中使用赋值
- next.js - Gatsby 或 NextJS 用于电子商务复杂网站
- svelte - 在苗条上安装美人鱼
- kubernetes-helm - 将字符串转换为 YAML 映射
- python - 如何在python中的两个数据框之间添加列并按条件填充它的值
- c++ - Boolean stop signal between threads
- google-cloud-platform - 停止和启动 vm 实例后 GCP 的 SSH 终端不工作