我想弄清楚如何从一个文本文件中列出两个分开名字和DOB的列表。我在文本文件中看到了如下示例:
"Bob Willus, 03/25/1993"
但我的文本文件如下所示:
James B W Bevis
10/12/1943
Henry Bemis
8/4/2008
Romney Wordsworth
8/29/2012
到目前为止,这就是我所拥有的:
file = open("contactsLab4.txt.","r")
names = []
birthdate = []
for line in file:
splitLine = line.split("\n")
names.append(splitLine[0])
birthdate.append(splitLine[0])
print(names)
print(birthdate)
这就是结果:
['James B W Bevis', '10/12/1943', 'Henry Bemis', '8/4/2008', 'Romney Wordsworth', '8/29/2012',
'Osborne Cox', '1/21/1989', 'Somerset Frisby', '9/5/2010', 'Revis Jacara', '2/16/1935', 'Bartlet
Finchley', '11/30/2001', 'Penthor Mul', '5/3/1928', 'Walter Bedeker', '4/27/1996', 'Clegg Forbes',
'3/18/2004', 'Jeremy Wickwire', '12/9/1999', 'Luther Dongle', '7/24/1978', 'Klim Dokachin',
'10/1/1975', 'Archibald Beechcroft', '6/19/1991', 'Oliver Crangle', '5/6/1954', 'Agnes Grep',
'11/4/2013', 'William Feathersmith', '1/11/1967', 'Kalin Tros', '12/28/1955', 'Clovis Bagwell',
'7/19/2003', 'Wallace V Whipple', '3/8/1939', 'Jeff Myrtlebank', '8/23/2001', 'Latham Bine',
'2/2/1949', 'Jim Pembry', '4/1/1992']
['James B W Bevis', '10/12/1943', 'Henry Bemis', '8/4/2008', 'Romney Wordsworth', '8/29/2012',
'Osborne Cox', '1/21/1989', 'Somerset Frisby', '9/5/2010', 'Revis Jacara', '2/16/1935', 'Bartlet
Finchley', '11/30/2001', 'Penthor Mul', '5/3/1928', 'Walter Bedeker', '4/27/1996', 'Clegg Forbes',
'3/18/2004', 'Jeremy Wickwire', '12/9/1999', 'Luther Dongle', '7/24/1978', 'Klim Dokachin',
'10/1/1975', 'Archibald Beechcroft', '6/19/1991', 'Oliver Crangle', '5/6/1954', 'Agnes Grep',
'11/4/2013', 'William Feathersmith', '1/11/1967', 'Kalin Tros', '12/28/1955', 'Clovis Bagwell',
'7/19/2003', 'Wallace V Whipple', '3/8/1939', 'Jeff Myrtlebank', '8/23/2001', 'Latham Bine',
'2/2/1949', 'Jim Pembry', '4/1/1992']
请,谢谢
当然,这两种方法都是一样的,因为你没有对它们进行任何区分,你需要确定行中何时包含名称,何时包含日期,有多种方法可以做到这一点,这取决于数据的组织方式或给定行中包含的内容,例如,你可以检查行中的第一个字符是什么,如果它是一个数字,您可以假定它是一个日期,否则您可以假定它是一个名称:
我已经用
isDigit()
函数解决了您的问题:您提供的输入是:
您的输出和我提供的代码将是:
您可以这样做,因为名称和DOB在单独的行中
您可以使用
rstrip
自动删除换行符相关问题 更多 >
编程相关推荐