I’m new to python and am trying to puzzle out the use of the lambda function. I have two lists of network user names in a text file which I need to match. The code I have so far works okay(it matches names but is case sensitive), but the text in both these files is a mishmash of upper and lower case. I may have smith, john (FINANCE) in one list and SMITH,John (Finance) in another. There will be hundreds of user text files.What I need to do is normalize both lists (to upper case for example) so matches occur regardless of case. My lack of python knowledge is hampering me. I have the following
with open (filename, "r") as file1:
#file1m=map(lambda x: x.upper(),file1)
for line in islice(file1,20,None)
with open ("c:\\userlists\test.txt", "r") as file2:
But, to be honest I don't know where the lambda function sits in that bit of code. I've tried it where you see the hash, but python never seems to make a username match. I know I need to do upper case file2, but for this test, and to simplify the process for me, I've added a few names in upper case in test.txt to see if it works. Without the lambda function, as mentioned my code does what I need and matches username but is case sensitive. Any help would be really appreciated.
Many thanks
You could create a simple Context Manager to allow the files to be converted to uppercase transparently as they're read. Here's an example of what I'm suggesting:
from itertools import imap
class OpenUpperCase(object):
def __init__(self, *args, **kwargs):
self.file = open(*args, **kwargs)
def __enter__(self):
return imap(lambda s: s.upper(), self.file)
def __exit__( self, type, value, tb ):
self.file.close()
return False # allow any exceptions to be processed normally
if __name__ == '__main__':
from itertools import islice
filename1 = 'file1.txt'
with OpenUpperCase(filename1, "r") as file1:
for line in islice(file1, 20, None):
print line, # will be uppercased