用python中的regex拆分文件

2024-05-19 00:43:28 发布

您现在位置:Python中文网/ 问答频道 /正文

有很多问题和我的差不多,但我还是没办法解决。我想看一份文件,得到相关信息。我正在尝试用python中的regex来实现它。你知道吗

文件副本:

       File name    : tmp2.jpg
       File size    : 179544 bytes
       File date    : 2003:03:29 10:58:40
       Camera make  : Canon
       Camera model : Canon DIGITAL IXUS 300
       Date/Time    : 2002:05:19 18:10:03
       Resolution   : 1200 x 1600
       Flash used   : Yes
       Focal length : 11.4mm  (35mm equivalent: 79mm)
       CCD width    : 5.23mm
       Exposure time: 0.017 s  (1/60)
       Aperture     : f/4.0
       Focus dist.  : 1.17m
       Exposure bias:-0.33
       Metering Mode: matrix
       Jpeg process : Baseline

我正在尝试的是:

  infile = sys.argv[1]
  ifile = open(infile, 'r').read()

  myInfo = re.split('\s*\n:', ifile)

  for x in range(len(myInfo)):

       if myInfo[x] == 'Date/Time':
            print x
            x = x + 1

它需要做什么:

我需要得到这个信息:2002:05:19 18:10:03 从此行开始:日期/时间:2002:05:19 18:10:03

为什么我不能分开:空间和新线?你知道吗


Tags: 文件信息datetime副本infileregexfile
2条回答

我不想用read()。你不需要一次在你的程序中使用所有的数据。只需遍历文件的每一行。你知道吗

import io
data = """       File name    : tmp2.jpg
       File size    : 179544 bytes
       File date    : 2003:03:29 10:58:40
       Camera make  : Canon
       Camera model : Canon DIGITAL IXUS 300
       Date/Time    : 2002:05:19 18:10:03
       Resolution   : 1200 x 1600
       Flash used   : Yes
       Focal length : 11.4mm  (35mm equivalent: 79mm)
       CCD width    : 5.23mm
       Exposure time: 0.017 s  (1/60)
       Aperture     : f/4.0
       Focus dist.  : 1.17m
       Exposure bias:-0.33
       Metering Mode: matrix
       Jpeg process : Baseline"""

for line in io.StringIO(data):
    if line.strip().startswith('Date/Time'):
        datetime = line.split(':', 1)[1].strip()
print(datetime)

你不需要正则表达式。使用^{}^{}。你知道吗

>>> 'Date/Time    : 2002:05:19 18:10:03'.split(':', 1)
['Date/Time    ', ' 2002:05:19 18:10:03']
>>> name, value = map(str.strip, 'Date/Time    : 2002:05:19 18:10:03'.split(':', 1))
>>> name
'Date/Time'
>>> value
'2002:05:19 18:10:03'

相关问题 更多 >

    热门问题