gpt4 book ai didi

python - Mad lib Python,为什么下面的循环不能正常工作?

转载 作者:行者123 更新时间:2023-12-01 09:10:34 25 4
gpt4 key购买 nike

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

我刚刚开始练习 python 2.7。在这个疯狂的库练习中,我被要求根据随机函数用字符串替换任何名词/动词,并在执行此替换后返回输出字符串。我被困在粗体线“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)

最佳答案

你的解决方案很难遵循并且非常不符合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()))

关于python - Mad lib Python,为什么下面的循环不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com