Python从文件中提取数据并写入到anoth

2024-09-29 23:17:25 发布

您现在位置: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>

对于文件的第一个区域,我需要输出文件Morgen 1.txt 包含以下内容:

^{pr2}$

我从其他用户那里得到这个代码:

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)

但它不起作用


Tags: and文件textrehereisnumberscontains
3条回答

看看这对你是否有用:

#!/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

如果您想要一种快速而肮脏的方法来完成此操作,而不使用xml(推荐),这将完成以下工作:

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)

试试这个。。。它起作用了。。。在

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;

相关问题 更多 >

    热门问题