2013-05-30 26 views
0

我是新來的python,我試圖解開使用lambda函數。我有兩個需要匹配的文本文件中的網絡用戶名列表。我到目前爲止的代碼工作正常(它匹配名稱但區分大小寫),但這兩個文件中的文本都是大寫和小寫混雜。我可能有史密斯,約翰(金融)在一個名單和史密斯,約翰(金融)在另一個。將會有數百個用戶文本文件。我需要做的是對兩個列表進行標準化(例如以大寫字母爲例),因此無論大小寫如何匹配。我缺乏Python知識阻礙了我。我有以下幾點Python Lambda地圖

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: 

但是,老實說,我不知道lambda函數位於該位代碼的位置。我試過了,你看到的散列,但python永遠不會使用戶名匹配。我知道我需要做大寫的file2,但是對於這個測試,爲了簡化這個過程,我在test.txt中添加了一些大寫字母的名字,以查看它是否有效。沒有lambda函數,如上所述我的代碼做我需要和匹配的用戶名,但區分大小寫。任何幫助將非常感激。

非常感謝

+0

取消註釋您的第二行,然後使用file1m而不是file1以後 – njzk2

+0

謝謝。我試過,並使用file1m(所以大寫的文件1)python似乎並沒有匹配。 IDLE只是坐在那裏,我不得不用鍵盤打破。 – user2377057

回答

1

您可以創建一個簡單的Context Manager允許文件轉換爲他們讀透明大寫。下面是我建議的示例:

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 
+0

謝謝@馬蒂奧。這真的很有意義,是一個很好的答案。我可以看到我的列表都以大寫字母打印。現在,我希望我不想在這裏留下月球,但我似乎無法獲得一場比賽。我用於我在file1中,爲file2中的j,希望得到一個i == j。那麼,我需要做什麼?作爲S.O newb和Python newb的道歉,我不知道如何回答以下問題。 – user2377057

+0

非常感謝@martineau。我已經找出代碼在你的幫助下失敗的地方。最好的祝願 – user2377057

1

您可以使用此將文件轉換爲大寫。然後,你可以做你想要的東西。或者你可以使用下面的代碼作爲一個想法,並使其適應你正在嘗試做的事情。

file1 = "C:/temp/file1.txt" # first file 
file2 = "C:/temp/file2.txt" # second file 

m_upper = lambda x: x.upper() # uppercase lambda function. 

# open the files, read them, map using the mapper, 
# and write them back with append. 
def map_file(file_path, append='_upper', mapper=m_upper): 
    file_name, ext = file_path.rsplit('.', 1) 
    new_fp = '%s%s.%s' % (file_name, append, ext) 
    with open(file_path) as f_in, open(new_fp, 'w') as f_out: 
     f_out.write(''.join(map(mapper, f_in))) 

map_file(file1) # file1.txt -> file1_upper.txt (all uppercase) 
map_file(file2) # file2.txt -> file2_upper.txt (all uppercase) 
+0

感謝您的幫助。如果需要,我會試一試並報告。 – user2377057