-2

I would like to refactor this code to take in unknown parameters. What I mean is that right now it looks through a a list of URLS (ex: http://www.blahblah.com/something/somethingelse?a=8&b=2&c=3). The code is splitting upon the query(?) and then splitting again upon the ampersand(&). After it splits, the part that is split (i.e: a=b) is put into an appropriately named file (a_file.txt). The thing is, what if my program runs into an unknown parameter that is not in the hash list? The information would be lost, I presume. So my question is whether Python has functions that can, A. build a brand new file that was not in the hash list before and name it appropriately and B. put the information into a file such as (char_file.txt). So, if there is an unknown character, make a file for it and append the information into it. Any help is appreciated.

import urlparse
def parse_file(input_file):
    tags = {tag: tag + '_file.txt' for tag in {'blog',
        'p','attachment_id','lang',
        'portfolio','page_id','comments_popup',
        'iframe','width','height'}}
    with open(input_file) as input:
        for line in input:
            parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query)
            if parsed_url > 0:
                for key, value in parsed_url:
                    if key in tags:
                        with open(tags[key], 'a') as output_file:
                            output_file.write(value)
                    else:
                        print key + " not in tags."
             else:
                 print(line + " does not yield query.")

parse_file()

1 Answer 1

0

Why do you have that tags variable? Just do the same thing you're doing currently, but leave the whole tags thing out, and it should work like a charm. Opening a file in "a"-mode creates it, if it doesn't exist yet.

Replace

for key, value in parsed_url:
    if key in tags:
        with open(tags[key], 'a') as output_file:
            output_file.write(value)
    else:
        print key + " not in tags."

with

for key, value in parsed_url:
    with open(key+"_file.txt", 'a') as output_file:
        output_file.write(value)

Then, you can of course also remove the tags declaration at the top

2
  • btw, I apologize in advance, I am new to programming. Nov 11, 2013 at 20:35
  • like this: import urlparse def parse_file(input_file): with open(input_file) as input: for line in input: parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query) if parsed_url > 0: for key, value in parsed_url: with open(key+"_file.txt", 'a') as output_file: output_file.write(value) else: print(line + " does not yield query.") parse_file() Nov 11, 2013 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.