仅打印 .txt 文件中的特定单词 - Python
Printing only specific words from .txt file - Python
对于以下问题的任何帮助将不胜感激。
我有以下名为 DOB 的 .txt 文件:
Orville Wright 21 July 1988
Rogelio Holloway 13 September 1988
Marjorie Figueroa 9 October 1988
Debra Garner 7 February 1988
Tiffany Peters 25 July 1988
Hugh Foster 2 June 1988
Darren Christensen 21 January 1988
Shelia Harrison 28 July 1988
Ignacio James 12 September 1988
Jerry Keller 30 February 1988
Frankie Cobb 1 July 1988
Clayton Thomas 10 December 1988
Laura Reyes 9 November 1988
Danny Jensen 19 September 1988
Sabrina Garcia 20 October 1988
Winifred Wood 27 July 1988
Juan Kennedy 4 March 1988
Nina Beck 7 May 1988
Tanya Marshall 22 May 1988
Kelly Gardner 16 August 1988
Cristina Ortega 13 January 1988
Guy Carr 21 June 1988
Geneva Martinez 5 September 1988
Ricardo Howell 23 December 1988
Bernadette Rios 19 July 1988
我需要按照以下格式示例打印所有姓名和出生日期:
Name:
O Wright
Birthdate:
21 July 1988
我的下面代码打印出我需要的大写字母中的第一个字符,但是我如何将之后的特定单词分开并从 txt 文件中打印出来?
我目前的代码是:
f = open('DOB.txt', 'r+')
for line in f:
f = line[0] + ". "
print(f)
g = open('DOB.txt')
for g in g.read().split():
print(g)
假设每个名字只是名字和姓氏,没有中间名等。您可以简单地读取文件的每一行并根据白色拆分 space。下面将捕获 first 和 last 中的第一个 to 字段,然后是 dob 中的其余字段。然后我们可以使用我们的变量打印这两行。不需要遍历文件数据两次。
with open('test.txt') as my_file:
for person in my_file:
first, last, *dob = person.rstrip().split()
print(f"Name: {first[0]}. {last}")
print(f"Birthdate: {' '.join(dob)}")
输出
Name: O. Wright
Birthdate: 21 July 1988
Name: R. Holloway
Birthdate: 13 September 1988
Name: M. Figueroa
Birthdate: 9 October 1988
对于以下问题的任何帮助将不胜感激。
我有以下名为 DOB 的 .txt 文件:
Orville Wright 21 July 1988
Rogelio Holloway 13 September 1988
Marjorie Figueroa 9 October 1988
Debra Garner 7 February 1988
Tiffany Peters 25 July 1988
Hugh Foster 2 June 1988
Darren Christensen 21 January 1988
Shelia Harrison 28 July 1988
Ignacio James 12 September 1988
Jerry Keller 30 February 1988
Frankie Cobb 1 July 1988
Clayton Thomas 10 December 1988
Laura Reyes 9 November 1988
Danny Jensen 19 September 1988
Sabrina Garcia 20 October 1988
Winifred Wood 27 July 1988
Juan Kennedy 4 March 1988
Nina Beck 7 May 1988
Tanya Marshall 22 May 1988
Kelly Gardner 16 August 1988
Cristina Ortega 13 January 1988
Guy Carr 21 June 1988
Geneva Martinez 5 September 1988
Ricardo Howell 23 December 1988
Bernadette Rios 19 July 1988
我需要按照以下格式示例打印所有姓名和出生日期:
Name:
O Wright
Birthdate:
21 July 1988
我的下面代码打印出我需要的大写字母中的第一个字符,但是我如何将之后的特定单词分开并从 txt 文件中打印出来?
我目前的代码是:
f = open('DOB.txt', 'r+')
for line in f:
f = line[0] + ". "
print(f)
g = open('DOB.txt')
for g in g.read().split():
print(g)
假设每个名字只是名字和姓氏,没有中间名等。您可以简单地读取文件的每一行并根据白色拆分 space。下面将捕获 first 和 last 中的第一个 to 字段,然后是 dob 中的其余字段。然后我们可以使用我们的变量打印这两行。不需要遍历文件数据两次。
with open('test.txt') as my_file:
for person in my_file:
first, last, *dob = person.rstrip().split()
print(f"Name: {first[0]}. {last}")
print(f"Birthdate: {' '.join(dob)}")
输出
Name: O. Wright
Birthdate: 21 July 1988
Name: R. Holloway
Birthdate: 13 September 1988
Name: M. Figueroa
Birthdate: 9 October 1988