我需要创建一个程序来对文本文件中的“姓名”和“出生日期”进行分组,然后将它们打印到两个不同的部分。
Orville Wright 21 July 1988 '\n'
Rogelio Holloway 13 September 1988 '\n'
Marjorie Figueroa 9 October 1988 '\n'
Debra Garner 7 February 1988 '\n'
Tiffany Peters 25 July 1988 '\n'
Hugh Foster 2 June 1988 '\n'
Darren Christensen 21 January 1988 '\n'
Shelia Harrison 28 July 1988 '\n'
Ignacio James 12 September 1988 '\n'
Jerry Keller 30 February 1988 '\n'
Frankie Cobb 1 July 1988 '\n'
Clayton Thomas 10 December 1988 '\n'
Laura Reyes 9 November 1988 '\n'
Danny Jensen 19 September 1988 '\n'
Sabrina Garcia 20 October 1988 '\n'
Winifred Wood 27 July 1988 '\n'
Juan Kennedy 4 March 1988 '\n'
Nina Beck 7 May 1988 '\n'
Tanya Marshall 22 May 1988 '\n'
Kelly Gardner 16 August 1988 '\n'
Cristina Ortega 13 January 1988 '\n'
Guy Carr 21 June 1988 '\n'
Geneva Martinez 5 September 1988 '\n'
Ricardo Howell 23 December 1988 '\n'
Bernadette Rios 19 July 1988][1] '\n'
Name (heading)
1. A Masinga '\n'
Etc. '\n'
Birth date (heading)
1. 21 July 1988 '\n'
Etc. '\n'
我正在尝试将每行的前两个单词分开,并在名为“名称”的标题下打印它们,并将每行的后三个单词,在“出生日期”下打印。我已经尝试了许多方法,但似乎无法正确完成。
name = []
birthday = []
f = open("DOB.txt","r+")
lines = f.readlines()
lines[0:26]
for words in lines:
if name(lines.split()[:2]): #first two strings are name
print(name,lines)
if birthday(words.split()[-3:]): #last three strings are the birthday
print(birthday)
f.close()
答案 0 :(得分:0)
您的代码的主要问题是:
if name(lines.split()[:2])
...
if birthday(words.split()[-3:])
...
name
和birthday
是list
,所以我不确定通过将它们称为函数(name()
)和{{ 1}})。我认为您要尝试将字符串存储到birthday()
和name
中。为此,birthday
具有一种append
方法,用于将“ 一个项目添加到列表的末尾”。
另一个问题是,您正在循环中list
立即{b1}交替输入名称和bday。您可以先存储所有名称和生日,然后稍后再打印。
尝试一下:
print