【问题标题】:Mad lib Python, why the loop below is not working properly?Mad lib Python,为什么下面的循环不能正常工作?
【发布时间】:2018-08-05 08:28:40
【问题描述】:

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

我刚开始练习 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)

【问题讨论】:

  • 首先,请格式化您的代码。
  • 感谢@DYZ 指出这一点,刚刚编辑了它:)
  • 您的第一个函数可以(并且可能应该)重写为return random.choice(["run","kayak"])。与第二个函数相同。
  • 您不能在代码中设置文本格式。编辑修复
  • @TrooperZ 添加了您的更改,谢谢!

标签: python python-2.7


【解决方案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())) 

【讨论】:

  • 超级@DYZ,谢谢!!!我看到我缺少很多内置工具。我浏览了您的答案,并且效果很好。我会更新上面的代码:)
  • 如果您没有其他问题,您应该接受答案。如果您仍有疑问,您应该更新原始帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多