-1

我需要帮助从文本文件中导入这样的数据:

奥维尔赖特 1988 年 7 月 21 日

罗杰里奥·霍洛威 1988 年 9 月 13 日

玛乔丽·菲格罗亚 1988 年 10 月 9 日

并将其显示在 python shell 上,如下所示:

姓名

  1. O.赖特
  2. R·霍洛威
  3. M.菲格罗亚

出生日期

  1. 1988 年 7 月 21 日
  2. 1988 年 9 月 13 日
  3. 1988 年 10 月 9 日
4

1 回答 1

-1

将文件行读入列表 在 Python 中,如何将文件逐行读入列表中?

枚举 https://docs.python.org/2.3/whatsnew/section-enumerate.html

with open('filename') as f:
  lines = f.readlines()  # see above link
  names = []  # list of 2-element lists to store names
  timestamps = []  # list of 3-element lists to store timestamps as day/month/year 

  # preprocess 
  for line in lines:
    a = line.split(" ")  # the delimiter you use appears to be a space
    names.append(a[:2])  # everything up to and excluding third item after split
    timestamps.append(a[2:])  # everything else

  # output
  print("some header here") # put whatever you want here
  for i, name in enumerate(names):  # see enumeration reference
    # you could add a length check on name[0] in case first name is blank
    print("{}. {}. {}".format(str(i+1), name[0][0], name[1]))  
  print("another header here") # again use whatever header you want here
  for i, timestamp in enumerate(timestamps):
    print("{}. {}".format(str(i+1), " ".join(timestamp))  
于 2018-05-07T18:55:55.270 回答