2012-12-22 142 views
-3

我是python中的新成員,需要幫助。 我有一個文件,並希望提取文本到另一個文件。Python從文件中提取數據並寫入另一個

輸入文件看起來是這樣的:

<Datei Kennung="4bc78" Titel="Morgen 1" Bereich="I847YP"> Morgen 1 

Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 

</Datei> 
<Datei Kennung="469" Titel="Trop Hall W " Bereich="izr"> Trop Hall W 

Here is text, contains numbers and text. 
Here is text, contains numbers and text.  


</Datei> 

對於我的文件中第一個區域,我需要爲摩根的1.txt 的文件,其中包含這樣的輸出:

Morgen 1 

Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 
Here is text, contains numbers and text. 

我從拿到其他用戶本代碼:

import re 
REG_PARSE=re.compile(r'<Datei[^>]*Titel="\s*([^"]*?)\s*"[^>]*>\s*\1\s*(.*?</Datei>',re.dotall) 
with open(filename) as infile: 
for outfilename, text = REG_PARSE.finditer(infile.read()): 
    with open('%s.txt'%outfilename,'w') as outf: 
     outf.write(text) 

但它不起作用

+0

使用['lxml.etree'(http://lxml.de/)讀取INFILE,因爲它似乎是XML格式。然後使用普通的[file-io](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)寫入另一個文件。此外,你到目前爲止嘗試過什麼? – inspectorG4dget

+1

老兄,請編輯您的問題,而不是發表評論與代碼 – inspectorG4dget

+0

我已經盡我所能將您的代碼添加到您的OP。請確認它是正確的 – inspectorG4dget

回答

-2

如果你想快速和骯髒的方式做到這一點,而不使用XML(推薦)嘗試了這一點...它的作品...

fp = open("data.txt", "r") 
data = fp.read(); 

data = data.split(">"); 

i = 0; 

while True: 
    filename = data[i].split('" ')[1].split('"')[1] 
    text = data[i+1].split('<')[0].strip() 

    fp1 = open(filename + ".txt", "w") 
    fp1.write(text) 
    fp1.close() 

    i += 2 
    if i >= (len(data) - 1): 
     break; 
+0

脆弱的修飾代碼.... –

+0

嗨,這工作完美。 – user1923258

+0

非常感謝。祝聖誕快樂能和你和家人在一起。 – user1923258

-1

,這將做的工作:

with open('path/to/input') as infile: 
    found = False 
    outfile = open("Morgen 1.txt", 'w') 
    for line in infile: 
     if line.startswith("<Datei") and 'Titel="Morgen 1"' in line: 
      found = True 
     elif line.startswith("</Datei"): 
      found = False 
     if found: 
      if not line.startswith("<Datei"): 
       outfile.write(line) 
+0

感謝您的回答,但其他代碼完全適合我。我希望你和家人聖誕快樂。 – user1923258

0

看看這對你的作品:

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 
from xml.dom import minidom 
xmldoc = minidom.parse('/path/to/file') 
items = xmldoc.getElementsByTagName('Datei') 

for s in items: 
    if s.attributes['Titel'].value == "Morgen 1": 
     with open("Morgen 1.txt", "w") as fileOutput: 
      listLines = [ line.strip() 
          for line in s.firstChild.nodeValue.strip().split("\n") 
          if line.strip() 
          ] 

      fileOutput.write("\n".join(listLines)) 
      break 
相關問題