Python

Moderators: None (Apply to moderate this forum)
Number of threads: 400
Number of posts: 1055

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Python Programming help please Posted by Vikram_cyclone on 16 Jun 2010 at 11:00 PM
Hi there,

I got this txt file with following contents:

<GLOSSARY>
<INFO>
<NAME>My Glossary</NAME>
<INTRO>stuff</INTRO>

The above text is saved in test.txt file.

I need to write a python script that would load the above file as list of strings. I then need display only the text from <Name> to </Name> in python.

If anybody can help me please with the code. I've tried searching a lot on net but haven't found anything.

Thank You
Report
Re: Python Programming help please Posted by bubbatremell on 18 Jun 2010 at 10:09 AM
import re

name_block = re.compile('<Name>(?P<name>.*)</Name>')

def get_name_block():
    #open the file for reading
    file_name = "test.txt"
    f = open(file_name, 'r')
    
    #look through it one line at a time
    name_block = ""
    search_result = None
    for l in f:
        search_result = name_block.match(l)
        if search_result:
            name_block = search_result.groups[0]
    return name_block


That will have a problem if <Name>...</Name> spans over multiple lines, because "for l in f" pulls one line at a time. In that case, no one line would ever match the regex. Hope that works for you!




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.