我想从现有的文本文件中选择一个随机记录,并以特定格式显示信息。例如,仅在一个字段中看到每个单词的首字母。
import random
graderecord=random.choice(grade.readlines())
field=graderecord.split(",")
name=field[0]
expected_grade=field[1]
actual_grade=field[2]
words=name.split()
initials=""
for word in words:
initials=initials+word[0]
此刻,我的程序在文件“学生姓名缩写,预期成绩,实际成绩”中显示了我想要的一条记录的结果。如何重复此操作,以便在需要时可以显示另一个记录?
答案 0 :(得分:0)
只需在接受字符串列表的函数中抽象代码即可:
def get_random_record(records):
graderecord = random.choice(records)
field = graderecord.split(",")
name = field[0]
expected_grade = field[1]
actual_grade = field[2]
words = name.split()
initials = ""
for word in words:
initials = initials+word[0]
return initials
records = grade.readlines()
for i in range(10):
print(get_random_record(records))