疯狂的lib Python,为什么下面的循环无法正常工作?

时间:2018-08-04 23:03:18

标签: python python-2.7

更新:在第一个答案之后,顶部代码将提供预期的输出。

我刚刚开始练习python 2.7。在这个疯狂的lib练习中,我被要求根据随机函数用字符串替换任何NOUN / VERB并在执行此替换后返回输出字符串。我被困在粗体线“ i = space_pos + 1”,我认为在确定了空格/位置之后,我应该从空格之后的下一个位置再次运行循环。

工作代码:

import random

def random_verb():
   return random.choice(["run","kayak"])

def random_noun():
   return random.choice(["sofa","llama"])

def word_transformer(word):
   if word == "NOUN":
      return random_noun()
   elif word == "VERB":
      return random_verb()
   else:
      return word

def process_madlib(mad_lib):
   # Split the string into words
   words = mad_lib.split() 
   # Apply a transformation to each word
   transformed = map(word_transformer, words)
   # Join the transformed words
   return " ".join(transformed) 

#test-output 
test_string_1 = "This is a good NOUN to use when you VERB your food"
test_string_2 = "I'm going to VERB to the store and pick up a NOUN or 
                   two."
print process_madlib(test_string_1)
print process_madlib(test_string_2)

#old non working version 
from random import randint

def random_verb():
    random_num = randint(0, 1)
    if random_num == 0:
        return "run"
    else:
       return "kayak"

def random_noun():
    random_num = randint(0,1)
    if random_num == 0:
       return "sofa"
    else:
       return "llama"

def word_transformer(word):
    if word == "NOUN":
        return random_noun()
    elif word == "VERB":
        return random_verb()
    else:
        return word

def process_madlib(mad_lib):
    processed = ""
    i = 0
    while (i < len(mad_lib)):
      space_pos = mad_lib.find(' ', i)                #find space_pos: 4 
      word = mad_lib[i:space_pos]                     #ex: This
      processed += word_transformer(word)             #check "This" VS 
      i = space_pos +1 #This is the problem line      #NOUN/VERB          
                                               #start loop after the space, 
                                               #at pos:5 to check new word                                   
    return processed                           #(is)



test_string_1 = "This is a good NOUN to use when you VERB your food"
print process_madlib(test_string_1)

1 个答案:

答案 0 :(得分:1)

您的解决方案很难遵循,而且非常不符合Python规范。考虑使用Python强大工具:拆分,列表理解和联接。

def process_madlib(mad_lib):
    # Split the string into words
    words = mad_lib.split() 
    # Apply a transformation to each word
    transformed = [word_transformer(word) for word in words]
    # Join the transformed words
    return " ".join(transformed) 

函数主体的第二行可以进一步重写为映射:

    transformed = map(word_transformer, words)

最后,整个功能可以实现为单行:

def process_madlib(mad_lib):
    return " ".join(map(word_transformer, mad_lib.split()))