Search in textfiles?
aleaxit at yahoo.com
Mon May 14 10:48:45 CEST 2001
"Martin Johansson" <045521104 at telia.com> wrote in message
news:_gML6.10366$sk3.2783263 at newsb.telia.net...
> import string
> word = raw_input("Write a word ")
> c=open('10 Maj 08_580,2183,106_nyheter_1022,00.html.txt', 'r')
> textstring = c.read()
> index = string.find(textstring, word)
> if index > 0:
> print "yes the word exists in the textfile"
> print "it doesn´t exist"
> this code I rote, but what can be done if big letters should not be
> different than small letters?
> (Martin should be the same as martin)
Simplest is to lowercase both the string you're looking for
and the one into which you're looking, changing the 2nd and
3rd lines of this snippet as follows:
textstring = c.read().lower()
index = textstring.find(word.lower())
If for some reason you're still using a very old Python and
so can't use methods of string objects, you may equivalently
call string.lower() on the string of which you want to get
the lowercased equivalent.
There are alternatives, such as using regular expressions
and the case-insensitive-search flag you can pass when you
compile a regular expression, but just lowercasing the
strings before the search is simpler in most use-cases.
More information about the Python-list