【问题标题】:Extracting different Data from a txt file in python从python中的txt文件中提取不同的数据
【发布时间】:2020-11-26 03:38:25
【问题描述】:

我一直在尝试从 txt 文件中提取数据

这是文本文件:

PARTIALRUN,0
time,2020-07-31 12:21:44
update,5.8.6.32
build,2319
comments,testing
BaseDir,\\Testing\Python\2020_07_31_12_21_44

我想从文本文件中提取一些信息来获取这些信息

WeekNumber= 31
5.8.6.32NUMBER2319

这就是我尝试的方式:

test_array =[]
with open ('file_location', 'rt') as testfile:
    for line in testfile:
        firsthalf, secondhalf =(
            item.strip() for item in line.split(',', 1))
        date = tuple(map(int, secondhalf.split('-')))
        datetime.date(date).isocalendar()[1]
        weekNumber= "Week Number: " + str(datetime.date(date).isocalendar()[1])
        print(workWeek)
        buildnumber = secondhalf[2] + "NUMBER" + secondhalf[3]
        print(buildnumber)  

我收到的错误:

>    buildnumber = secondhalf[2] + "NUMBER" + secondhalf[3]
>IndexError: string index out of range

>    datetime.date(date).isocalendar()[1]
>TypeError: an integer is required (got type tuple)

我对 python 还很陌生,所以非常感谢任何帮助

【问题讨论】:

    标签: python file split extract


    【解决方案1】:

    您可以使用re 获取所需的号码。对于第二个错误,使用星号* 解包元组:

    import re
    from datetime import date
    
    
    txt = r'''PARTIALRUN,0
    time,2020-07-31 12:21:44
    update,5.8.6.32
    build,2319
    comments,testing
    BaseDir,\\Testing\Python\2020_07_31_12_21_44'''
    
    t = re.search(r'time,([^\s]+)', txt).group(1)
    t = tuple(map(int, t.split('-')))
    u = re.search(r'update,(.*)', txt).group(1)
    b = re.search(r'build,(.*)', txt).group(1)
    
    print('WeekNumber= {}'.format(date(*t).isocalendar()[1]))
    print('{}NUMBER{}'.format(u, b))
    

    打印:

    WeekNumber= 31
    5.8.6.32NUMBER2319
    

    编辑:(从文件中读取):

    import re
    from datetime import date
    
    
    with open('file_location', 'r') as f_in:
        txt = f_in.read()
    
    t = re.search(r'time,([^\s]+)', txt).group(1)
    t = tuple(map(int, t.split('-')))
    u = re.search(r'update,(.*)', txt).group(1)
    b = re.search(r'build,(.*)', txt).group(1)
    
    print('WeekNumber= {}'.format(date(*t).isocalendar()[1]))
    print('{}NUMBER{}'.format(u, b))
    

    【讨论】:

    • 谢谢,这很有帮助!我一直在尝试使用您正在做的事情,但仍然没有将 txt 文件粘贴到代码中。我试图让程序读取 txt 文件并提取信息。有什么建议吗?
    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2017-09-16
    相关资源
    最近更新 更多