2014-11-25 68 views
0

我有這個函數是從另一個文件填充自己。我很難避免以;;;開頭的txt文件的頭文件。而且字典的第一個方面應該是大寫的單詞,接下來的是音素。我不知道這是我的代碼部分是錯誤的:S如何從文件中填充字典而忽略標題?

def read_file(file): 
    """ (file open for reading) -> pronunciation dictionary 

    Read file, which is in the format of the CMU Pronouncing 
    Dictionary, and return the pronunciation dictionary. 
    """ 
    line = file.readline() 
    while line != ';;;': 
     line = file.readline() 
    pronun_dict = {} 
    line = file.readline() 
    while line != '': 
     word = line.isupper() 
     phoneme = line.strip() 
     if phoneme not in pronun_dict: 
      pronun_dict[phoneme] = [word] 
     line = file.readline() 
    return pronun_dict 

http://gyazo.com/31b414c39cc907bc917f7a1129f4019d 上面的鏈接是一個什麼樣的文本文件看起來像一個屏幕截圖!

+0

在python中有一個dictreader類。你嘗試使用是嗎? – 2014-11-25 05:07:44

+0

您可以顯示文本文件的樣本嗎? – thefourtheye 2014-11-25 05:16:27

+0

@thefourtheye :)我發佈了一個文本文件的樣子! – 2014-11-25 05:38:35

回答

0

while line != ';;;':只有當標題不完全匹配';;;'時纔會被滿足。我假設標題可以包含更多的數據。試試,而不是while line.startswith(';;;'):。只要滿足該條件,文件中的下一行將被分配給變量line。因此,您的代碼將遍歷該塊,直到找到不以​​開頭的行。

http://www.tutorialspoint.com/python/string_startswith.htm