Read and count
Mark Lawrence
breamoreboy at yahoo.co.uk
Thu Mar 10 04:23:33 EST 2016
Hello and welcome.
Please see my comments below.
On 09/03/2016 21:30, Val Krem via Python-list wrote:
> Hi all,
>
> I am a new learner about python (moving from R to python) and trying read and count the number of observation by year for each city.
>
> The data set look like
> city year x
>
> XC1 2001 10
> XC1 2001 20
> XC1 2002 20
> XC1 2002 10
> XC1 2002 10
>
> Yv2 2001 10
> Yv2 2002 20
> Yv2 2002 20
> Yv2 2002 10
> Yv2 2002 10
>
> out put will be
>
> city
> xc1 2001 2
> xc1 2002 3
> yv1 2001 1
> yv2 2002 3
>
>
> Below is my starting code
> count=0
Seems like you'd want a counter here
https://docs.python.org/3/library/collections.html#collections.Counter.
You'll need to know how to import this so start here
https://docs.python.org/3/tutorial/modules.html
> fo=open("dat", "r+")
We'd normally use the 'with' keyword here so the file automatically gets
closed so:-
with open("dat", "r+") as fo:
> str = fo.read();
'str' isn't a good name as it overrides the builtin function of that
name. This will read the entire file. Easiest to loop as in:-
for line in fo.readlines():
Now you'll need a split call to get at your data
https://docs.python.org/3/library/stdtypes.html#str.split and update
your counter. Once this loop is finished use another loop to produce
your output with print.
> print "Read String is : ", str
The above is for Python 2, it needs parenthesis for Python 3. I'd
recommend starting with the latter if that's possible.
>
> fo.close()
Not needed if you use the 'with' keyword as discussed above.
>
> Many thanks
>
No problem as I'm leaving you to put it all together :)
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-list
mailing list