[Tutor] running split and count + looping to check for numbers in same line

Kent Johnson kent37 at tds.net
Thu Feb 11 03:50:53 CET 2010


On Wed, Feb 10, 2010 at 6:43 PM, jim serson <fubarninja at hotmail.com> wrote:
> I am getting an error when I try and run split and count I seem to get it to
> work with one or the other but not together. python wants a character buffer
> but I am not sure how to use it.
>
> I would also like to use readline to check and see if several numbers are in
> the same line but I think I will need to use it in a loop maybe for? So it
> would check for the first then check for the second if both are true add to
> count but if ether are false continue to next line and repeat.
>
> If anyone can help me that would be grate.
> Thanks
>
> look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ")
> search = raw_input ("Enter your search item ").split

Here search is actually a function because you left out the
parentheses after split(). But with them, search would be a list. The
argument to count() must be a string.
> file = open(look_in, "r").read().count(search)
> print "Your search came",file ,"times"

Do you want a count per line or for the whole file? For the whole file
you could do something like

search_terms = raw_input ("Enter your search item ").split()  # Note
the final ()
data = open(look_in).read()
count = 0
for term in search_terms:
  count += data.count(term)

The last three lines could also be written as
count = sum(data.count(term) for term in search_terms)

Kent


More information about the Tutor mailing list