如何在忽略标题的同时从文件中填充字典?

时间:2014-11-25 04:59:19

标签: python

我有这个功能,可以从另一个文件填充自己。我很难避免以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 上面的链接是文本文件的截图!

1 个答案:

答案 0 :(得分:0)

仅当标题与“#;;;;'”完全匹配时,才会遇到

while line != ';;;':。我假设标头可以包含更多数据。请尝试while line.startswith(';;;'):。只要满足此条件,文件中的下一行将分配给变量line。因此,您的代码将遍历该块,直到找到不以;;;开头的行。

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