Does some part of code blocks the other part

This is the place for queries that don't fit in any of the other categories.

Does some part of code blocks the other part

Postby compileandrun » Fri May 24, 2013 3:39 pm

I am totally new to programming. I did some basic C and now learn Python from google classes.
In the current code I try to extract two different information set from the same file and store in different variables.

Code: Select all
def extract_names(filename):
    year=[]
    names=[]
    population=re.search(r'(popularity\sin\s)(\d+)',filename.read(),re.IGNORECASE)
    print population.group(2)
    year.append(population.group(2))
    baby=re.findall(r'(<td>)(\d+)',filename.read())
    for tuple in baby:
        names.append(tuple[1])
    print names

The result of this code is:
>>>
1990
[]
>>>


When I run this code, my 'names' variable is returned empty. If I comment some parts of the lines (as it stands below), I see everything is stored in 'names' variable correctly.
Code: Select all
def extract_names(filename):
    year=[]
    names=[]
    #population=re.search(r'(popularity\sin\s)(\d+)',filename.read(),re.IGNORECASE)
    #print population.group(2)
    #year.append(population.group(2))
    baby=re.findall(r'(<td>)(\d+)',filename.read())
    for tuple in baby:
        names.append(tuple[1])
    print names

Result now is:
['1', '2', '3', '4', '5', '6',.......'994', '995', '996', '997', '998', '999', '1000']

Edit: Edited according to the advice below.
Last edited by compileandrun on Fri May 24, 2013 4:08 pm, edited 3 times in total.
compileandrun
 
Posts: 1
Joined: Fri May 24, 2013 3:34 pm

Re: Does some part of code blocks the other part

Postby Yoriz » Fri May 24, 2013 3:52 pm

Hi you would need to supply the following to stand more chance of getting help with your question.

    A runnable sample of your code with the correct indenting.
    A sample of what the file you are reading contains.
    Your expected output

Note: becarefull with asigning names ie you have an assignment to reserved built-in symbol: tuple

Please have a read of this post http://www.python-forum.org/viewtopic.php?f=10&t=145
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Yoriz
 
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Does some part of code blocks the other part

Postby hansn » Fri May 24, 2013 4:35 pm

My best guess is that your baby variable is empty because you call "filename.read()" twice.

Try doing .read() twice on a file in your interpreter and you will see what i mean.
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 7 guests