练习Python:打开文本Fi

2024-09-30 04:39:53 发布

您现在位置: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)

有人能帮忙吗?我不能使用可视化工具,因为程序无法读取我的文件。在


Tags: 文件程序httpwwwcontentsopenfileprint
1条回答
网友
1楼 · 发布于 2024-09-30 04:39:53

I can't use a visualizer

您只需定义您自己的file_contents列表。。。在

无论如何,您可能需要在其他地方检查Reading a file line by line in 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)

相关问题 更多 >

    热门问题