gpt4 book ai didi

python - 在 Python 中,如何用列表中的随机项替换字符串中的单词?

转载 作者:太空宇宙 更新时间:2023-11-04 07:00:50 25 4
gpt4 key购买 nike

我正在尝试采用某种字符格式 _n_ 并将其替换为数组中的随机字符串。

在 wordlibrary.py 中:

    import random

nouns = ['wombat','zebra','elephant','lamp','desk','computer','python','castle','king','scribble','doodle','motorcycle','car','train','plane']

def chooseNoun():
randomNoun = random.randint(0,len(nouns))
nounChoice = nouns[randomNoun-1]
return nounChoice

现在,在 storyCreator.py 中:

    import wordLibrary

originalString = input("Type a sentence or story. Use \'_n_\' to denote a noun, \'_adj_\' to denote an adjective, \'_v_\' to denote a verb, \'_adv_\' to denote an adverb, or \'_l_\' to denote a location. Type Here: ")

nounCheck = '_n_'

如何在字符串中找到 _n_ 并每次用列表中的随机单词替换它?

最佳答案

同时使用str.replacerandom.choice,并记得分配新的字符串:

while '_n_' in oldString:
oldString = oldString.replace('_n_', random.choice(nouns))

关于python - 在 Python 中,如何用列表中的随机项替换字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245001/

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