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

时间:2011-12-19 03:36:07

标签: python string list for-loop

我正在进行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 个答案:

答案 0 :(得分:2)

你可能想要:

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

在内循环中,您当然希望再次分割句子,而不是文字

答案 1 :(得分:2)

TypeError:并非在字符串格式化期间转换所有参数

是暗示。

你的循环很好。

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

错了。

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

之后的值

数字不一样,是吗?那是TypeError

答案 2 :(得分: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)) 
  1. 如果我理解正确,您希望按分隔.分割句子。然后,您希望将这些句子中的每一个分割为由,再次分隔的短语。所以你的第二行实际上应该拆分外循环枚举的输出。像

    这样的东西
    for p, phrase in enumerate(sentence.split(',')):
    
  2. 打印声明。如果您看到类似TypeError的错误,则可以确定您尝试将一种类型的变量分配给另一种类型。好吧,但没有任务?它是对打印串联的间接分配。您对该印刷品的承诺是,您将提供3个参数,其中前两个参数为Integers(%d),最后一个为string(%d)。但您最终提供的3 Integers s+1p+1len(sentence)phrase)与您的打印格式说明符不一致。您可以删除第三个参数(len(sentence)),如

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

    或将另外一个Format Specifier添加到print语句

    print('sentence #%d:, phrase #%d:, length #%d, %s' %(s+1,p+1,len(sentence),phrase)) 
    
  3. 假设你想要前者,那就让我们

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

答案 3 :(得分:0)

>>> sen = [words[1] for words in enumerate(text.split(". "))]
>>> for each in sen: each.split(", ")
['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.']

您可以根据自己的喜好转换此未分配的输出。