[Tutor] Count Help
Konrad Korżel
konrad.korzel at gmail.com
Fri Oct 25 17:42:28 CEST 2013
It's better to use the "with open" statement to open the file and then
process it line by line with occurrence counter, like:
def occurence(pathToFile, substring):
substringCount = 0
with open(pathToFile, 'r') as src:
for line in src:
substringCount += line.count(substring)
return substringCount
On 24 October 2013 17:01, Dave Angel <davea at davea.name> wrote:
> 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list