2016-03-22 163 views
0

我需要從文本文件的行中提取數據。數據是名稱和得分信息格式如下:從python提取文件的數據

Feature_Locations: 
    - { x:9.0745818614959717e-01, y:2.8846755623817444e-01, 
     z:3.5268107056617737e-01 } 
    - { x:1.1413983106613159e+00, y:2.7305576205253601e-01, 
     z:4.4357028603553772e-01 } 
    - { x:1.7582545280456543e+00, y:2.2776308655738831e-01, 
     z:6.6982054710388184e-01 } 
    - { x:9.6545284986495972e-01, y:2.8368893265724182e-01, 
     z:3.6416915059089661e-01 } 
    - { x:1.2183872461318970e+00, y:2.7094465494155884e-01, 
     z:4.5954680442810059e-01 } 

此文件由其他軟件生成。 基本上我想獲得這些數據早在這個節目,我想將它們保存在不同的其他文件的例子「axeX.txt」「axeY.txt」「axeZ.txt」

我試試這個

import numpy as np 
import matplotlib.pyplot as plt 
import re 
file = open('data.txt', "r") 
for r in file: 
    y = re.sub("- {", "",r).split() 
    tt = y[:2] 
    zz = tt 
    st = re.findall('\d+', r) 
    print st 
file.close() 

有沒有更好的方法或我做錯了?

回答

0

你可以嘗試這樣的:

s = open('data.txt', "r").read() 

x = re.findall(r'x:(.*), ', s) 
y = re.findall(r'y:(.*),', s) 
z = re.findall(r'z:(.*) ', s) 

with open('axeX.txt', 'w') as f: f.write('\n'.join(x)) 
with open('axeY.txt', 'w') as f: f.write('\n'.join(y)) 
with open('axeZ.txt', 'w') as f: f.write('\n'.join(z)) 
+0

工作正常!非常感謝 ! :D – ahmed

1

輸入文件是YAML格式。建議使用PyYAML包解析yaml文件。

import yaml 

document = """ 
Feature_Locations: 
    - { x: 9.0745818614959717e-01, y: 2.8846755623817444e-01, 
     z: 3.5268107056617737e-01 } 
    - { x: 1.1413983106613159e+00, y: 2.7305576205253601e-01, 
     z: 4.4357028603553772e-01 } 
    - { x: 1.7582545280456543e+00, y: 2.2776308655738831e-01, 
     z: 6.6982054710388184e-01 } 
    - { x: 9.6545284986495972e-01, y: 2.8368893265724182e-01, 
     z: 3.6416915059089661e-01 } 
    - { x: 1.2183872461318970e+00, y: 2.7094465494155884e-01, 
     z: 4.5954680442810059e-01 } 
""" 

locations = yaml.load(document)['Feature_Locations'] 

for ch in 'XYZ': 
    fname = 'axe%s.txt' %ch 
    with open(fname, 'w') as fh: 
     for item in locations: 
      fh.write('%s\n' % item[ch.lower()]) 

輸入文件略有損壞。 yamllint將做一個健全性檢查,並通知我們有關錯誤。

yamllint inputfile.yaml 
inputfile.yaml 
    1:1  warning missing document start "---" (document-start) 
    2:9  error syntax error: found unexpected ':' 

在這種情況下,我們可以很容易地修復輸入文件。

sed -i 's/:/: /g' inputfile.yaml 
+0

您似乎必須通過在變量(x,y,z)和實際值之間添加空格來預處理文檔。使用PyYAML有沒有直接的方法? –