【问题标题】:Keeping random name in Python在 Python 中保持随机名称
【发布时间】:2017-08-27 17:52:29
【问题描述】:

我正在学习 Python,并拼凑了一个随机句子生成器来练习。如何为后续部分保留第一个随机选择的名称?

我有这个:

def random_name():
    line_num = 0
    selected_line = ''
    with open('names.txt') as f:
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
            selected_line = line
    return selected_line.strip()

重复动词和名词。然后我定义句子:

def MakeSentence(): #makes sentence by combining name, verb, and noun

x = random_name() + " is " + random_verb() + " " + random_noun()
return x

print("Type Yes to continue.")
print("\n")
print("Enter 'Q' to quit.")
print("\n")
response = 'x' #generic response as to not cause problems

while (response != 'Q'): #case switch kills it all

response = input("Would you like to continue?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(MakeSentence())

response = input("Is " + random_name() + " correct?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(random_name() + " is correct.\n")

【问题讨论】:

  • 你需要知道我们很多/大多数人都不愿意通读这么多代码,更不用说调试了。你需要问一些简短的、具体的编程问题,这些问题有明确的答案。您可能应该阅读帮助文件。这并不是说以任何方式阻止您,只是告诉您期望什么。欢迎来到 SO!
  • 你一遍又一遍地打电话给random_name。你不能只调用一次并将结果存储在一个变量中吗?
  • 谢谢你们。以后我会尽量简洁。谢谢,Carcigenicate,我想你是对的 :)
  • def MakeSentence 周围的缩进是否正确?
  • 提示:不要使用while 1: ... 使用for line in f: ...,这将终止而无需中断。

标签: python random


【解决方案1】:

MakeSentence(): 一旦遇到 return 语句就结束,所以你有几个 print 语句在看似重复之后执行?

你可以让它返回一个列表或元组:

def MakeSentence(): #makes sentence by combining name, verb, and noun
    """
    (None)->List
    Returns a list with a random name, verb and noun
    """
    x = [random_name(), random_verb(), random_noun()]
    return x

你可以做很多这样的,例如,试试这个:

sample = MakeSentence()

并以上述格式打印:

print(sample[0] + " is " + sample[1] + " " + sample[2])

希望这可以为您解决问题!

如何存储要使用的第一个随机名称、动词和名词 进一步的陈述?

运行后,您可以看到解释器中发生了什么:该函数返回一个包含三个字符串的列表,您可以使用括号符号 [0]、[1] 和 [2] 来访问其中的每一个如下所示。这三样东西对你来说都是可用的,直到或者除非你覆盖它们。

>>> sample = MakeSentence()
>>> print(sample)
['Sean', 'eating', 'apples']
>>> print(sample[0] + " is " + sample[1] + " " + sample[2])
Sean is eating apples

如果我想获得很多样本,我可以这样做:

many_samples = []  # make a list to store many lists
for users in range(3):  # to generate three samples: change to larger number if desired
    many_samples.append(MakeSentence())

嵌套列表的一个例子可能是这样的(但重新排列以使其更易于阅读):

>>> print(many_samples)
[ 
  ['Sean', 'eating', 'apples'],
  ['Jane', 'drinking', 'oranges'],
  ['Jim', 'chopping', 'chairs']
]

# to print out these in a format as you had in the example:
for each_elem in many_samples:
    print(each_elem[0] + " is " + each_elem[1] + " " + each_elem[2])

所以我们正在遍历列表,列表中的每个元素都是另一个列表。 在每个子列表中,我们获取第一个(位置 0)、第二个和第三个(位置 2)元素并将它们插入到我们的字符串输出中。

【讨论】:

  • 谢谢。我已经尝试过了,但是当我添加 [0] 时,它最终只打印了名称的第一个字母。我究竟做错了什么?例如response = input("Is " + sample_name[0] + " 正确吗?\n") 给出:K 正确吗?
  • 我的目的是展示“如何存储第一个随机名称、动词和名词以用于进一步的陈述?”如果您只是调用函数 random_name() 来生成名称,那么只会返回一个字符串。访问字符串中的字符类似于访问列表中的元素,因此如果将字符串“Mike”分配给名为“name”的变量并打印出 name[0],则确实只会得到第一个字符。如果您需要,我可以添加另一个评论或更详细信息,或者另一个示例?我已经用上面的附加代码添加了一些细节和 cmets。 :)
  • 谢谢你,srattigan。你很有帮助:)
  • 如果上面的答案符合您的问题,请您选择它作为接受的答案吗?非常感谢,肖恩。
  • 谢谢。上面创建字符串的方法效果很好,而且很容易遵循,但是这里显示了一个更优雅的方法,您可能会在以后的版本中考虑:stackoverflow.com/questions/5082452/… 祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
  • 1970-01-01
  • 2015-10-28
相关资源
最近更新 更多