簡體   English   中英

從 python 中的 txt 文件中提取不同的數據

[英]Extracting different Data from a txt file in python

我一直在嘗試從 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 相當陌生,因此將不勝感激

您可以使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM