基于多个分隔符拆分字符串的嵌套循环
我正在做一个Python的作业,需要对文本进行分隔、排序并打印出来,具体要求是:
- 句子用
.
来分隔 - 短语用
,
来分隔 - 然后打印出来
到目前为止,我做了以下工作:
text = "what time of the day is it. i'm heading out to the ball park, with the kids, on this nice evening. are you willing to join me, on the walk to the park, tonight."
for i, phrase in enumerate(text.split(',')):
print('phrase #%d: %s' % (i+1,phrase)):
phrase #1: what time of the day is it. i'm heading out to the ball park
phrase #2: with the kids
phrase #3: on this nice evening. are you willing to join me
phrase #4: on the walk to the park
phrase #5: tonight.
我知道需要用到嵌套的for循环,并且尝试过:
for s, sentence in enumerate(text.split('.')):
for p, phrase in enumerate(text.split(',')):
print('sentence #%d:','phrase #%d: %s' %(s+1,p+1,len(sentence),phrase))
TypeError: not all arguments converted during string formatting
如果能给我一点提示或者简单的例子就太好了。
4 个回答
2
你可能想要的是:
'sentence #%d:\nphrase #%d: %d %s\n' %(s+1,p+1,len(sentence),phrase)
在里面的循环中,你肯定是想要对句子进行拆分,而不是再对文本进行拆分。
2
TypeError: 不是所有的参数都在字符串格式化时转换
这是一个提示。
你的循环写得没问题。
'sentence #%d:','phrase #%d: %s' %(s+1,p+1,len(sentence),phrase)
这里是错的。
数一数 %d
和 %s
这些格式化符号的数量。再数一数在 %
符号后面的值。
这两个数量是不是不一样?这就是一个 TypeError
错误。
1
你的代码片段有几个问题
for s, sentence in enumerate(text.split('.')):
for p, phrase in enumerate(text.split(',')):
print('sentence #%d:','phrase #%d: %s' %(s+1,p+1,len(sentence),phrase))
如果我理解得没错,你是想用
.
来分割句子。然后再把每个句子用,
来分割成短语。所以你第二行的代码其实应该是对外层循环的结果进行分割。可以这样写:for p, phrase in enumerate(sentence.split(',')):
关于打印语句。如果你看到类似
TypeError
的错误,那就说明你在尝试把一种类型的变量赋值给另一种类型。可是这里没有赋值?其实这是间接赋值给打印的拼接。你在打印时提供了3个参数,其中前两个应该是整数(%d)
,最后一个是字符串(%d)
。但你实际上提供了3个整数
(s+1
,p+1
,len(sentence)
,phrase
),这和你的打印格式不一致。你可以选择去掉第三个参数(len(sentence)
),像这样:print('sentence #%d:, phrase #%d: %s' %(s+1,p+1,phrase))
或者在打印语句中再加一个格式说明符
print('sentence #%d:, phrase #%d:, length #%d, %s' %(s+1,p+1,len(sentence),phrase))
假设你想要前者,这样我们就可以得到:
for s, sentence in enumerate(text.split('.')):
for p, phrase in enumerate(text.split(',')):
print('sentence #%d:, phrase #%d:, length #%d, %s' %(s+1,p+1,len(sentence),phrase))