0
def main():
    fname = input("Enter name of file: ")
    with open(fname) as inf:
        animalnames, dates, locations = zip(*[line.strip().split(':') for line in inf])

    d = {}
    for animalname, loc in zip(animalname, locations):
        d.setdefault(animalname, []).append(loc)  

    for k, v in d.items():
       print(k, end='\t')
       print(v.count('loc1'), end='\t')
       print(v.count('loc2'))        

main()

i have a txt file name animallog1.txt which contains the following

a01:01-24-2011:s1 
a03:01-24-2011:s2 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2  

i would like to use the above data which is in the format animaname:data:location to print the following table:

Number of times each animal visited each station : 
Animal name Station 1 Station 2 
a01         2         1 
a02         0         3 
a03         4         4 
========================================

i have tried and my code is what i have got, but it gives me the error

builtins.UnboundLocalError: local variable 'animalname' referenced before assignment

could someone help me fix this so i can get the desired result.

2 Answers 2

5

You might want to refer animalnames here

for animalname, loc in zip(animalnames, locations):
Sign up to request clarification or add additional context in comments.

1 Comment

i have another problem now, the table is not showing the right data, as it should contains numbers and not zeros....
0

In response to your second question, are you searching for the exact string names of the stations with count?

I see "loc1" and "loc2" are hard-coded into the provided snippet, and am wondering if that is just by way of example, or if the final script uses those instead of "s1" and "s2" or some flexible parameters.

2 Comments

i am pretty sure that i am not
Can you post the snippet that is returning 0 where you expect other numbers, and a short piece of a file you're parsing?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.