[Tutor] searching through a string list
Steve George
sgeorge@vianetworks.co.uk
09 Aug 2002 14:34:36 +0100
Hi Mathew,
I think my short example meets your request.
On Fri, 2002-08-09 at 02:22, Mathew P. wrote:
<snip>
> This list will have the same names in it more than once, and what I am
> actually doing is parsing the list to find out how many times a persons
> name appears in the list. To complicate things, I need to be able to do
> a partial match. For instance, I need to be able to find out how many
> "anthony" 's appear in the list - so if I have an anthony brown, and
> anthony johnson, and an anthony williams, the program will count three
> anthonys.
<snip>
#!/usr/bin/env python
import string
input_list = [ ['1', 'george'], ['2', 'simon'], ['3', 'john'], ['4',
'simon smith'] ]
output_dict = { }
search_term = "simon"
for x, y in input_list:
ret = y.find( search_term )
if ret >= 0:
if search_term in output_dict.keys():
output_dict[ search_term] += 1
else:
output_dict[search_term] = 1
print output_dict
The only downside with this logic is that it will also catch "john
anthony" or in my specific example 'simone' because Pythons string find
method will match any substring. You might want to consider the general
expression library if you need anything more complex.
Cheers,
Steve