On 23/10/2013 22:12, Jackie Canales wrote:

> let say i have a file with random letters of  A, AB, C, CD, AC, A, D, CD, DD, 
> C, B, AB, CD, AB
> How do i count the occurrence of each individual item.
>
> def occurence(name):
>     infile = open('bloodtype1.txt', 'r')
>     lst = infile.read()

read() doesn't return a list, it returns a string.  So the name is
poorly chosen.  Probably you wanted a list, with each item containing
one or two letters.

You can use split(",") to break the string into a list, based on commas.
And you can use strip() on each item of that list to get rid of
whitespace.


>     infile.close()
>
>     print(lst.count('AB')) # 3
>     print(lst.count('CD')) # 2
>     print(lst.count('DD'))# 1
>
>
> i know i can do lst.count("AB") it will give me 3 but if i were to do 
> lst.count("A") it would give me 6 what I am having trouble with is just 
> getting the occurrence of the A by itself to give me 1 since there is just 
> one occurrence of it and would need to do the same for c and d with out it 
> counting the them in the occurrence of AC and DD or CD.

When searching the original string, you have that problem.  Making an
actual list will fix it.


-- 
DaveA


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to