[Tutor] Problem creating a search

Luke Paireepinart rabidpoobear at gmail.com
Sun Jan 31 02:45:04 CET 2010


On Sat, Jan 30, 2010 at 4:42 PM, Shashwat Anand <anand.shashwat at gmail.com>wrote:

>
>
> On Sun, Jan 31, 2010 at 3:47 AM, jim serson <fubarninja at hotmail.com>wrote:
>
>>  Hi I am pretty new to python and programming in general. I am trying to
>> create a search that takes a user input for a file location and user input
>> to find a group of numbers or a phrase in that file count how many times it
>> appears then display it.
>>
>> I have gone through a tutorials and searched I/O to find the code I need.
>> Although I have not been able to make it work properly yet.
>>
>> I am able to open and read from the file the user would input but cant
>> seem to make the other input retrieve the numbers or phrase from the file or
>> have it count how many time it appears. If anyone can help or point me in
>> the right direction I would appreciate it. Thanks for your time.
>>
>> look_in = raw_input ("Enter the search file to look in ")
>> search = raw_input ("Enter your search item ")
>>
>    c = open(look_in, "r").read().count(search)
>    print c
>    if c:    print search, "your search was found"
>    else:    print "your search was not found"
>
> As Anand pointed out, in Python if you have a problem that you would think
would have a common (/ simple) solution, it probably does.  In this case you
can just read the whole file into a string and use a string method to count
the occurrences.  The disadvantage is that the file is then residing
completely in memory, which may not be ideal for larger files.  So in that
case you'll have to iterate over the file line-by-line, but you can still
use the count method to determine how many times an item occurs in each
line.
For example you could easily do something like this:

infile = raw_input("Input file: ")
search = raw_input("search term: ")
count = 0
for line in infile:
    count += line.count(search)


The key here is the "for line in infile" will not keep the whole file in
memory (at least I don't think it will, I believe that it's a generator so
it's yielding each line).  It probably will run more slowly than Anand's
solution, though.  Depends on your requirements.


Good luck with Python and hopefully we can help you with any other stumbling
blocks you might encounter while learning this wonderful language :)
-Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100130/3793ed9a/attachment.htm>


More information about the Tutor mailing list