Python 2.7文本文件数据处理求助:格式化输出姓名与出生日期
Solution for Python 2.7 Data Import & Formatting
Alright, let's break this down to get exactly the output you want. First, let's assume your text file (let's call it birth_data.txt) has the raw data as a single line of space-separated values:
Orville Wright 21 July 1988 Rogelio Holloway 13 September 1988 Marjorie Figueroa 9 October 1988
Here's a Python 2.7 script that reads this file, processes the data, and prints the formatted output in the shell:
# Open the text file and read its content with open('birth_data.txt', 'r') as file: # Split all content into a list of individual strings data = file.read().split() # Group the data into chunks of 5 elements (each chunk = [first_name, last_name, day, month, year]) people = [data[i:i+5] for i in range(0, len(data), 5)] # Extract formatted names (First initial + last name) and birth dates formatted_names = ["{0}. {1}".format(p[0][0], p[1]) for p in people] birth_dates = ["{0} {1} {2}".format(p[2], p[3], p[4]) for p in people] # Print the output in the required format print "Name" print " ".join(formatted_names) print "Birth date" print " ".join(birth_dates)
How this works:
- Reading the file: We use
with open(...)to safely open and read the file, then split the entire content into a list of strings using spaces as separators. - Grouping data: Using list slicing (
data[i:i+5]), we split the flat list into groups of 5 elements—each group represents one person's full name and birth date. - Formatting names: For each person, we take the first character of their first name (
p[0][0]), add a dot, then their last name. - Formatting dates: We combine the day, month, and year elements from each group into a single date string.
- Output: We print the headers "Name" and "Birth date" followed by the formatted values joined into space-separated lines.
When you run this script in Python 2.7 Shell, you'll get exactly the output you specified:
Name O. Wright R. Holloway M. Figueroa Birth date 21 July 1988 13 September 1988 9 October 1988
内容的提问来源于stack exchange,提问作者Zee Dhlomo
相关产品推荐
相关产品推荐

