【问题标题】:Extract lines from (oddly deliminated) txt file and write to new file with Python从(奇怪分隔的)文本文件中提取行并使用 Python 写入新文件
【发布时间】:2016-07-08 15:45:17
【问题描述】:

我有 .txt 文件(每张图片一个),其格式如下所示。但是,文件中使用的分隔符很奇怪。我不知道如何提取我感兴趣的信息。

ExifTool Version Number         : 10.20
File Name                       : R0010023.tiff
Directory                       : C:/gtag/wf1313
File Size                       : 46 MB
File Modification Date/Time     : 2016:07:07 20:57:38+01:00
File Access Date/Time           : 2016:07:07 20:57:38+01:00
File Creation Date/Time         : 2016:07:04 21:18:17+01:00
File Permissions                : rw-rw-rw-
File Type                       : TIFF
File Type Extension             : tif
MIME Type                       : image/tiff
Exif Byte Order                 : Little-endian (Intel, II)
Image Width                     : 4928
Image Height                    : 3264
Bits Per Sample                 : 8 8 8
Compression                     : PackBits
Photometric Interpretation      : RGB
Image Description               : 
Make                            : RICOH IMAGING COMPANY, LTD.
Camera Model Name               : GR II
Strip Offsets                   : (Binary data 558 bytes, use -b option to extract)
Orientation                     : Horizontal (normal)
Samples Per Pixel               : 3
Rows Per Strip                  : 51
Strip Byte Counts               : (Binary data 447 bytes, use -b option to extract)
X Resolution                    : 72
Y Resolution                    : 72
Planar Configuration            : Chunky
Resolution Unit                 : inches
Software                        : GR Firmware Ver 01.02
Modify Date                     : 2016:06:21 13:09:52
XMP Toolkit                     : Image::ExifTool 10.20
Compressed Bits Per Pixel       : 3.2
Flash Fired                     : False
Flash Function                  : False
Flash Red Eye Mode              : False
Flash Return                    : No return detection
Interoperability Index          : R98 - DCF basic file (sRGB)
Y Cb Cr Positioning             : Centered
Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
Copyright                       : 
Exposure Time                   : 1/1250
F Number                        : 6.3
ISO                             : 100
Sensitivity Type                : Standard Output Sensitivity
Exif Version                    : 0230
Date/Time Original              : 2016:06:21 13:09:52
Create Date                     : 2016:06:21 13:09:52
Components Configuration        : Y, Cb, Cr, -
Aperture Value                  : 6.3
Brightness Value                : 8.6
Exposure Compensation           : 0
Max Aperture Value              : 2.8
Metering Mode                   : Multi-segment
Light Source                    : Shade
Maker Note Type                 : Rdc
Firmware Version                : 1.02
Recording Format                : JPEG
Exposure Program                : Manual
Drive Mode                      : Single-frame
White Balance                   : Shade
White Balance Fine Tune         : 0 0
Focus Mode                      : Manual
Auto Bracketing                 : Off
Macro Mode                      : Off
Flash Mode                      : Off
Flash Exposure Comp             : 0
Manual Flash Output             : Full
Full Press Snap                 : Off
Dynamic Range Expansion         : Off
Noise Reduction                 : Weak
Image Effects                   : Standard
Vignetting                      : Off
Toning Effect                   : Off
Hue Adjust                      : Off
Focal Length                    : 18.3 mm
AF Area X Position 1            : 632
AF Area Y Position 1            : 418
AF Area X Position              : 2435
AF Area Y Position              : 1610
AF Status                       : In Focus
AF Area Mode                    : Auto
Sensor Width                    : 4928
Sensor Height                   : 3264
Cropped Image Width             : 4928
Cropped Image Height            : 3264
Wide Adapter                    : Not Attached
Color Temp Kelvin               : 0
Crop Mode 35mm                  : Off
ND Filter                       : Off
WB Bracket Shot Number          : 0
User Comment                    : 
Flashpix Version                : 0100
Color Space                     : sRGB
Exif Image Width                : 4928
Exif Image Height               : 3264
Exposure Mode                   : Manual
Focal Length In 35mm Format     : 28 mm
Scene Capture Type              : Standard
Contrast                        : Normal
Saturation                      : Normal
Sharpness                       : Normal
Owner Name                      : 
Serial Number                   : (00000000)14100511
Lens Info                       : 18.3mm f/2.8
Lens Make                       : RICOH IMAGING COMPANY, LTD.
Lens Model                      : GR LENS
GPS Version ID                  : 2.3.0.0
GPS Latitude Ref                : xxxx
GPS Longitude Ref               : xxxx
GPS Altitude Ref                : Above Sea Level
GPS Time Stamp                  : 12:09:52
GPS Img Direction Ref           : True North
GPS Img Direction               : 228.21
GPS Date Stamp                  : 2016:06:21
GPS Pitch                       : 0.79
GPS Roll                        : 0.41
PrintIM Version                 : 0300
Aperture                        : 6.3
Flash                           : Off, Did not fire
GPS Altitude                    : 91.7 m Above Sea Level
GPS Date/Time                   : 2016:06:21 12:09:52Z
GPS Latitude                    : xx deg xx' x.xx" N
GPS Longitude                   : x deg x' xx.xx" W
GPS Position                    : xx deg xx' x.xx" N, x deg x' xx.xx" W
Image Size                      : 4928x3264
Megapixels                      : 16.1
Scale Factor To 35 mm Equivalent: 1.5
Shutter Speed                   : 1/1250
Circle Of Confusion             : 0.020 mm
Field Of View                   : 65.5 deg
Focal Length                    : 18.3 mm (35 mm equivalent: 28.0 mm)
Hyperfocal Distance             : 2.71 m
Light Value                     : 15.6

如果我尝试以下示例,则会返回以下内容,

sfile = open("R001.txt", "r")
sfile.readline(1)

'E'

sfile.readline(2)

'xi'

sfile.readline(3)

'fTo'

sfile.readline(4)

'ol V'

sfile.readline(5)

'ersio'

等等等等。谁能告诉我如何处理这种类型的文件?

我感兴趣的是提取几行,

文件名 GPS 经度、GPS 纬度等。

如果有任何帮助,我将不胜感激。

问候 乔尔

编辑/更新

非常感谢 cmets!我真的很感激!

我现在有以下,

import glob
file_list = glob.glob("*.txt")

for file_ in file_list:
    saved_lines = []
    sfile = open(file_, "r")
    lines = sfile.readlines() #array of all lines
    for line in lines:
        for text in ['File Name', 'GPS Longitude', 'GPS Latitude', 'GPS Altitude', 'GPS Img Direction', 'GPS Pitch', 'GPS Roll']:
            if text in line:
                saved_lines.append(line)
    parsed = "".join(saved_lines) #reassemble the file
    with open("parsed.txt", "a") as ofile: #write your output
        ofile.write(parsed)

dict={}
sfile = open("R0010022.txt", "r")
list = sfile.readlines()
for i in list:
    dict[i.split(':')[0]] = ''.join(i.split(':')[1:])

我现在面临的挑战是我需要将数据格式化为以下格式(以便能够将其导入我想使用的程序中),

"#image latitude    longitude   altitude    yaw pitch   roll"
"R001.JPG   xx.xxxx y.yyyy  zzz.zz  319.9   8.2 -2.1"
"R002.JPG   xx.xxxx y.yyyy  zzz.zz  319.4   10.1    3.6"

所以每张图片用上面的数据一行。

如上所述创建字典是很好的第一步(我认为)。但是,字典很难调用,因为字典的每个成员在成员名称后都有不同数量的空格。即,文件名------------------------:...等等。

有没有办法查找成员,不包括空格?

如果可以的话,应该可以对每个图像进行分组,然后将每个组写入 .csv 或 .txt 文件中的单独行。

【问题讨论】:

  • 你没有看到这里的模式?您是否尝试不带参数地致电readline
  • 你知道这个文件的编码是什么吗?
  • @Scott Hunter 如果我调用 'readline()' 我会得到以下信息,'ExifTool 版本号:10.20\n'
  • @Xander 我不确定如何检查文件的编码。你能解释一下怎么做吗?

标签: python gps


【解决方案1】:

当您调用 readline(1) 时,您将收到第一行的 1 个字符。当您调用 readline(2) 时,您将收到第一行的 next 2 个字符,依此类推。当您点击新行时,它将在第二行继续。

打电话给readline(),不带参数,你会得到整行。

如果你想要几行,你可以使用readlines(),它返回一个包含文本文件中所有行的字符串列表。然后,您可以像使用普通列表一样提取它们。

更多信息请阅读python docs

【讨论】:

  • 谢谢!非常简单。我曾在某个时候使用过'readlines()',但我并没有想到将它写入指定的列表。再次感谢您!
【解决方案2】:

正如 Scott Hunter 指出的那样(间接地),您不是逐行读取文件。如果您查看了 readline 的文档,您会发现不带参数调用它会读取一整行,而使用数字参数调用它会读取那么多 bytes,而不是 lines时间>。

所以sfile.readline(1) 读取文件的第一个字节 ('E') 并将指针递增到该点。 sfile.readline(2) 然后从该点接管并读取接下来的两个字节 ('xi')。

从那里开始等等。

相反,您可能想做这样的事情:

saved_lines = []
sfile = open("R001.txt", "r")
lines = sfile.readlines() #array of all lines
for line in lines:
    for text in ['File Name', 'GPS Longitude', 'GPS Latitude']:
        if text in line:
            saved_lines.append(line)
parsed = "".join(saved_lines) #reassemble the file
with open("R001_PARSED.txt", "w") as ofile: #write your output
    ofile.write(parsed)

【讨论】:

  • “Oblique”是我的中间名!
  • 尝试在您的密钥上使用 .rstrip() 方法。 dict[i.split(':')[0]] = ''.join(i.split(':')[1:]) 变为 dict[i.split(':')[0].rstrip()] = ''.join(i.split(':')[1:])。 .rstrip()(不带参数调用时)删除所有尾随空格。
【解决方案3】:

由换行符分隔。

试试sfile.readlines()

然后要获取文件名,您应该将其转换为字典。因此,遍历您制作的列表中的每一项:

dict={}

for i in list:
    dict[i.split(':')[0]] = ''.join(i.split(':')[1:])}

或者如果您总是知道文件名在哪一行,只需使用list[X]

【讨论】:

  • 谢谢!对此,我真的非常感激!在您的回答的帮助下,我现在更新了问题。
【解决方案4】:

试试下面的, 打开你的文件

    File = opem("R001.txt", "r")

然后将数据读入列表,

    lstGPSData = File.readlines()

然后使用 split 函数进入不同的行,如果你想访问每一行,你可以使用索引

    For data in lstGPSData:
        lstValues = data.split(":")
        title = String(lstValue[0])
        value = String(lstValue[1])

再一次,如果你要在每一行的末尾加上一个逗号 (,),你可以将 split 参数更改为:

     lstValues = data.split(",")

然后你就不需要单独访问它们了

如果您需要更多,请查看GIS Programming

【讨论】:

  • 希望它不是一个非常大的文件。 (它的 EXIF,所以它不应该是。)
  • 感谢您的评论!我将使用 GPS 数据进行相当多的操作,以使该站点看起来很有用!不过,我并没有完全让您的代码正常工作(可能是因为我是新手……)。这就是我写的,' sfile = open("R001.txt", "r") title=[] value=[] lstGPSData = sfile.readlines() for data in lstGPSData: lstValues = data.split(":" ) title = str(lstValues[0]) value = str(lstValues[1])' 如果我调用 title 我得到 Light Value,如果我调用 value 我得到 15.6\n。但是我还没有弄清楚如何调用其余的值(标题和值)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 2020-03-26
  • 2014-02-15
相关资源
最近更新 更多