Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
文本文件处理,数据准备,日期时间格式,列表中的列表python程序问题的唯一问题_Python_Date_Dictionary - Fatal编程技术网

文本文件处理,数据准备,日期时间格式,列表中的列表python程序问题的唯一问题

文本文件处理,数据准备,日期时间格式,列表中的列表python程序问题的唯一问题,python,date,dictionary,Python,Date,Dictionary,问题如下: 唐纳德·约翰·特朗普(出生于1946年6月14日)担任第45任总统 2017年1月20日担任美国总统。从那天起,, 五位前美国总统同时健在 美国历史上只有四个时期 情况就是这样: 1861年3月4日至1862年1月18日:马丁·范布伦、约翰·泰勒、, 米勒德·菲尔莫、富兰克林·皮尔斯、詹姆斯·布坎南 1993年1月20日至1994年4月22日:理查德·尼克松、杰拉尔德·福特、吉米 卡特、罗纳德·里根、乔治·H·W·布什 2001年1月20日至2004年6月5日:杰拉尔德·福特、吉米·

问题如下:

唐纳德·约翰·特朗普(出生于1946年6月14日)担任第45任总统 2017年1月20日担任美国总统。从那天起,, 五位前美国总统同时健在 美国历史上只有四个时期 情况就是这样:

1861年3月4日至1862年1月18日:马丁·范布伦、约翰·泰勒、, 米勒德·菲尔莫、富兰克林·皮尔斯、詹姆斯·布坎南

1993年1月20日至1994年4月22日:理查德·尼克松、杰拉尔德·福特、吉米 卡特、罗纳德·里根、乔治·H·W·布什

2001年1月20日至2004年6月5日:杰拉尔德·福特、吉米·卡特、罗纳德 里根、乔治·H·W·布什、比尔·克林顿

2017年1月20日至2018年11月30日:吉米·卡特、乔治·H·W·布什、, 比尔·克林顿、乔治·W·布什、巴拉克·奥巴马

赫伯特·胡佛在死后又活了11553天(31岁230天) 离开办公室。詹姆斯·波尔克死后仅三个月(103天) 辞去总统职务。在当选为美国总统的个人中, 8人从未获得“前总统”的地位,因为他们 死于办公室:威廉·H·哈里森(肺炎),扎卡里·泰勒 (胆汁性腹泻)、亚伯拉罕·林肯(遇刺)、詹姆斯·加菲尔德 (被暗杀)、威廉·麦金利(被暗杀)、沃伦·G·哈丁 (心脏病发作)、富兰克林·D·罗斯福(脑出血)和约翰 肯尼迪(被暗杀)

在这个问题中,我们将处理包含信息的文本文件 关于某一特定国家元首的寿命和任期。每个 行包含五个选项卡分隔的信息字段:i)头部名称 州,ii)出生日期,iii)(第一个学期开始日期,iv)(最后一个) 学期结束日期和v)死亡日期。中给出了四个日期字段 格式为dd/mm/yyyy,每个片段为自然数,不带 前导零:dd表示日,mm表示月,yyyy表示年。 以下链接显示包含以下内容的tecxt文件的内容 关于美国最后十任总统的信息

[1] :

如果一位国家元首曾多次非连续任职,我们 假设他仅连续任职一届 从第一学期的开始日期到学期的结束日期 上学期。如果国家元首今天仍然在任,那末 他的任期日期由一个空字符串表示。以防头部受伤 州政府今天仍然活着,死亡日期由 空字符串

我需要编写一个函数
headsOfState
,它获取一个文本文件的位置,该文件包含关于特定国家元首的寿命和任期的信息。函数必须返回一个字典,该字典将文件中所有国家元首的姓名映射到一个元组上,元组中包含文件中提到的四个事件的日期(datetime.date对象),其出现顺序与文件中相同。尚未发生的事件的日期必须用值
None
表示

下面是我的代码:

from datetime import date
def headsOfState(filepath_of_workdir):
    open_file = open(filepath_of_workdir, 'r', encoding='utf-8')
    '''accessesing the text file from working directory. here we are \
        creating a list of lists of all words line wise using (readlines)'''
    content = open_file.readlines()    
    open_file.close()   
    content_list  = []  
    for i in range(len(content)):
        content_list.append(content[i].split('\t')) 
    prez_list = []
    for i in range(len(content_list)):
        prez_list.append(content_list[i][0])
        del (content_list[i][0])
    #print(prez_list)
    #print(content_list)
    temp_date = None
    inter_date_list = []    
    final_date_list = []
    for i in range(len(content_list)):
        temp_date = (content_list[i])      
        for j in range(len(temp_date)):
            item1 = temp_date[j].strip()
            item2 = item1.split('/')               
            if item2 == '' or item2 == ['\n']:
                inter_date_list.append(None)
            else:
                year = int(item2[2])
                month = int(item2[1])
                day = int(item2[0])
                inter_date_list.append(date(year, month, day))
                if len(inter_date_list) == len(content_list[i]):
                    final_date_list.append(inter_date_list)
        temp_date = None
        inter_date_list = []
    dict_prez = dict(zip(prez_list, final_list)) 

    return dict_prez
我得到以下错误:

headsOfState('us_presidents.txt')
Traceback (most recent call last):

  File "<ipython-input-66-1730ba5bcf8b>", line 1, in <module>
    headsOfState('us_presidents.txt')

  File "<ipython-input-65-1fbaf479e49a>", line 28, in headsOfState
    year = int(item2[2])

IndexError: list index out of range

请帮助我解决错误或提出更好的策略。

谢谢@mkrieger1。下面是我的最终代码。它起作用了

from datetime import date
def headsOfState(filepath_of_workdir):
    open_file = open(filepath_of_workdir, 'r', encoding='utf-8')
    '''accessesing the text file from working directory. here we are \
        creating a list of lists of all words line wise using (readlines)'''
    content = open_file.readlines()    
    open_file.close()
    '''creating an empty list for splitting the data at position with (\t)'''
    content_list  = []  
    '''adding the splitted data to the list'''
    for i in range(len(content)):
        content_list.append(content[i].split('\t')) 
    '''creating an empty list to add all president names to it and deleting the names\
        from content_list'''
    prez_list = []
    for i in range(len(content_list)):
        prez_list.append(content_list[i][0])
        del (content_list[i][0])
    '''creating an interim empty date list for date manipuation and empty final date list\
        for final tuple of dates in w.r.t. president names in prez_list'''
    inter_date_list = []    
    final_date_list = []
    for i in range(len(content_list)):
        temp_date = content_list[i]

        for j in range(len(temp_date)):
            item1 = temp_date[j].strip()

            item2 = item1.split('/') 

            '''creating integer for year, month and day for datetime format'''
            if len(item2) >1:
                year = int(item2[2])
                month = int(item2[1])
                day = int(item2[0])
                inter_date_list.append(date(year, month, day))
        while len(inter_date_list) <= 3: 
            inter_date_list.append(None)
        '''adding the dates for respective presidents to final list as tuple'''
        final_date_list.append(tuple(inter_date_list))
        '''emptying the inter_date_list for next list of dates from content_list'''
        inter_date_list = [] 
    '''creating the dictionary with keys as president names and values as date tuples'''
    dict_prez = dict(zip(prez_list, final_date_list))

    return dict_prez
from datetime导入日期
def headsOfState(工作区的文件路径):
open_file=open(workdir'r',encoding='utf-8'的文件路径_)
''从工作目录访问文本文件。我们到了\
使用(readlines)“”创建所有单词的逐行列表
content=打开文件.readlines()
打开_文件。关闭()
''正在创建一个空列表,用于在位置处使用(\t)拆分数据''
内容列表=[]
''正在将拆分的数据添加到列表''
对于范围内的i(len(content)):
content\u list.append(content[i].split('\t'))
''创建一个空列表,向其中添加所有总统姓名,并删除这些姓名\
从内容列表“”中
prez_列表=[]
对于范围内的i(len(内容列表)):
prez_list.append(content_list[i][0])
del(内容列表[i][0])
''为日期管理创建临时空日期列表和空最终日期列表\
对于prez_列表“”中的w.r.t.总统姓名中的最后日期元组
内部日期列表=[]
最终日期列表=[]
对于范围内的i(len(内容列表)):
临时日期=内容列表[i]
对于范围内的j(len(临时日期)):
item1=临时日期[j]。条带()
item2=item1.split(“/”)
''为datetime格式创建年、月和日的整数''
如果len(项目2)>1:
年份=整数(项目2[2])
月份=整数(项目2[1])
日期=整数(第2项[0])
inter_date_list.append(日期(年、月、日))

虽然len(inter_date_list)显然
item2
的项目少于3个,所以2是一个无效的索引。为什么您希望它有3个或更多项目?这是否回答了您的问题?非常感谢。你的指导很有帮助。我现在已经把代码设置好了。它起作用了。
from datetime import date
def headsOfState(filepath_of_workdir):
    open_file = open(filepath_of_workdir, 'r', encoding='utf-8')
    '''accessesing the text file from working directory. here we are \
        creating a list of lists of all words line wise using (readlines)'''
    content = open_file.readlines()    
    open_file.close()
    '''creating an empty list for splitting the data at position with (\t)'''
    content_list  = []  
    '''adding the splitted data to the list'''
    for i in range(len(content)):
        content_list.append(content[i].split('\t')) 
    '''creating an empty list to add all president names to it and deleting the names\
        from content_list'''
    prez_list = []
    for i in range(len(content_list)):
        prez_list.append(content_list[i][0])
        del (content_list[i][0])
    '''creating an interim empty date list for date manipuation and empty final date list\
        for final tuple of dates in w.r.t. president names in prez_list'''
    inter_date_list = []    
    final_date_list = []
    for i in range(len(content_list)):
        temp_date = content_list[i]

        for j in range(len(temp_date)):
            item1 = temp_date[j].strip()

            item2 = item1.split('/') 

            '''creating integer for year, month and day for datetime format'''
            if len(item2) >1:
                year = int(item2[2])
                month = int(item2[1])
                day = int(item2[0])
                inter_date_list.append(date(year, month, day))
        while len(inter_date_list) <= 3: 
            inter_date_list.append(None)
        '''adding the dates for respective presidents to final list as tuple'''
        final_date_list.append(tuple(inter_date_list))
        '''emptying the inter_date_list for next list of dates from content_list'''
        inter_date_list = [] 
    '''creating the dictionary with keys as president names and values as date tuples'''
    dict_prez = dict(zip(prez_list, final_date_list))

    return dict_prez