练习Python:打开文本文件



"练习python"上的问题:http://www.practicepython.org/exercise/2014/12/06/22-read-from-file.html

大家好,关于打开文件并检查内容的快速问题。该文件本身包含许多行,每条线都有Darth,Luke或Lea的名称。该程序应计算每个名称的数量。我想出了以下内容,但是当我运行程序时,什么也不会发生。

with open('PythonText.txt', 'r') as open_file:
    file_contents = open_file.readlines()
    ##Gives a list of all lines in the document##
    numberDarth = 0
    numberLea = 0
    numberLuke = 0
    numberNames = len(file_contents)-1
    while numberNames > 0:
        if file_contents[numberNames] == 'Darth':
            numberDarth = numberDarth + 1
            numberNames - 1
        elif file_contents[numberNames] == 'Lea' :
            numberLea = numberLea + 1
            numberNames - 1
        else:
            numberLuke = numberLuke + 1
            numberNames - 1
    pass
    print('Darth =' + numberDarth)
    print('Lea = ' + numberLea)
    print('Luke =' + numberLuke)

有人可以帮忙吗?我无法使用可视化器,因为程序无法读取我的文件。

我不能使用可视化器

您只能定义自己的file_contents列表...

无论如何,您可能需要在其他地方检查python中的线路。您无需将整个文件读取到列表中。这对大文件特别不好。

由于您仅扫描名称,只需挑选每行而不像以下那样存储其余的。

您也有一个随机的pass,它可能正在退出您的代码,什么也没打印。所以事情确实发生了...您只是什么都没有打印。当您学习调试事物时,它会鼓励您打印很多东西。

所以,我可能会用词典提出这样的建议。

,如果多个名称出现在同一行上,这也将计数。

name_counts = {'Darth': 0, 'Lea': 0, 'Luke': 0}
with open('PythonText.txt') as open_file:
    # For all lines
    for line in open_file:
        # For all names
        for name in name_counts:
            # If the name is in this line, count it
            if name in line:
                name_counts[name] += 1
print(name_counts)

最新更新