random.choice列表

时间:2016-07-22 06:03:06

标签: python random nlp

我有30个字符串的列表。我想使用随机模块的选择方法,并从它们存储的列表中生成一个新的字符串。我不想重复任何字符串,我想打印所有唯一的字符串一次。我正在尝试制作一个聊天机器人,但每次运行程序时,我只能得到1个字符串一遍又一遍地打印

print("you are speaking with Donald Trump. If you wish to finish your conversation at any time, type good bye")
greetings = ["hello", "hey", "what's up ?", "how is it going?", ]
#phrase_list = ["hello", "the wisdom you seek is inside you", "questions are more important than answers"]
random_greeting = random.choice(greetings)

print(random_greeting)
open_article = open(filePath, encoding= "utf8")

read_article = open_article.read()
toks = read_article.split('"')
random_tok = random.choice(toks)
conversation_length = 0
responses = ''

while True: #getting stuck in infinite loops get out and make interative
    user_response = input(" ")
    if user_response != "" or user_response != "good bye":
        responses = responses + user_response
        conversation_length = conversation_length + 1
    while conversation_length < 31:

        print(random_tok)
    if conversation_length >= 31:
        print("bye bye")

2 个答案:

答案 0 :(得分:0)

您需要“无需替换的随机选择”。调用字符串列表的此函数将返回一个随机字符串。被叫不止一次,它永远不会返回相同的项目。

import random

def choose_one(poss):
    """
    Remove a randomly chosen item from the given list, 
    and return it.
    """
    if not poss:
        raise ValueError('cannot choose from empty list')
    i = random.randint(0, len(poss) - 1)
    return poss.pop(i)

答案 1 :(得分:0)

不要使用random.choice()。使用random.shuffle()代替以随机顺序放置(唯一)单词,然后重复从该列表中取出。这确保了a)你使用了所有单词,并且b)不重复任何选择:

random_greetings = greetings[:]  # create a copy
random.shuffle(random_greetings)

然后只要你想要一个随机词,只需使用:

random_greeting = random.greetings.pop()