[Tutor] Count Help

Dave Angel davea at davea.name
Thu Oct 24 18:01:52 CEST 2013


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




More information about the Tutor mailing list