用于基于多个分隔符拆分字符串的嵌套for循环

2024-04-28 05:00:36 发布

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

我正在做一个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循环,并尝试过:

^{pr2}$

一个提示和/或一个简单的例子将受到欢迎。在


Tags: ofthetotextparktimeison
3条回答

TypeError:在字符串格式化过程中,并非所有参数都已转换

是个暗示。在

你的线圈很好。在

'sentence #%d:','phrase #%d: %s' %(s+1,p+1,len(sentence),phrase) 

是错误的。在

计算%d%s转换规范。计算%运算符/

数字不一样,是吗?这是一个TypeError。在

你的代码片段有几个问题

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)) 
  1. 如果我没听错,你想用分隔符.来分割句子。然后这些句子中的每一个都要拆分成短语,这些短语又用,分隔。所以第二行实际上应该分割outerloops枚举的输出。有点像

    for p, phrase in enumerate(sentence.split(',')):
    
  2. 打印声明。如果您遇到过类似TypeError的错误,您可以确定您正在尝试将一种类型的变量分配给另一种类型。但是没有任务?它是对打印连接的间接赋值。你对打印的承诺是,你将提供3个参数,其中前两个是Integers(%d),最后一个是string(%d)。但最后提供了3Integerss+1p+1len(sentence)phrase),这与打印格式说明符不一致。或者删除第三个参数(len(sentence)),如下所示

    print('sentence #%d:, phrase #%d: %s' %(s+1,p+1,phrase)) 
    

    或者在print语句中再添加一个格式说明符

    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)) 

你可能想要:

'sentence #%d:\nphrase #%d: %d %s\n' %(s+1,p+1,len(sentence),phrase)

在内部循环中,您当然希望分割句子,而不是文本

相关问题 更多 >