DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Basic Parser

11.25.2007
| 3487 views |
  • submit to reddit
        This is a very basic parser, reads each line and creates a string of ':'-separated id nos for mass-mailing a set of accounts in an online game

def joinIds(fin, fout):
    """reads a page from input file, joins Ids with ':'
    
    returns strings to output file, max of 50 ids in each"""
    lines = 0
    outlist = []
    for line in fin:
      if line.strip() != '':
        lines += 1
        outlist.append(line.split()[2])
        if lines % 50 == 0:
            fout.write(":".join(["%s" % Id for Id in outlist]) + "\n\n")
            outlist = []
    fout.write(":".join(["%s" % Id for Id in outlist]) + "\n\n")

try:
    SIA = raw_input('Enter a file to read: ')
    pages = open(SIA, 'r')
except IOError:
    print 'Cannot open file %s for reading. Check file exists and try again.' % SIA
    import sys
    sys.exit(0)
    

default = 'idFile.txt'
out = raw_input('File name for output: ')
if out == '':
    oFile = open(default, 'a')
else:
    default = out
    oFile = open(default, 'a')

joinIds(pages, oFile)
pages.close()
oFile.close()

print 'Id strings have been output to %s. Happy mass-mailing! ;)' % default