簡體   English   中英

在Python中,如何用列表中的隨機項替換字符串中的單詞?

[英]In Python, how might one replace a word within a string with a random item from a list?

我正在嘗試采用某種字符_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))

string.replace具有用於限制替換次數的參數。

在要修改的字符串中遍歷字符串出現的次數,並在每個循環中替換1次出現。

我相信您希望為_n_的每次出現都選擇一個新的隨機選擇。您可以將句子按空格分隔(對於更狡猾的解決方案,您可能希望使用re.findall代替),然后附加原始單詞或一個隨機單詞(如果字是_n_。

newString = []

for n in originalString.split():                                                                │
    newString.append(n=='_n_' and random.choice(nouns) or n)

' '.join(newString)

例:

“我的_n_確實很高,但不如我的_n_強。”

輸出:

“我的真的很高,但不如袋熊強。”

如果您可以使字符插入單詞{n}而不是_n_ ,則可以使用str.format()

originalString.format(n=random.choice(nouns), v=random.choice(verbs), adj=random.choice(adjectives), adv=random.choice(adverbs), l=random.choice(locations))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM