关于“练习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
列表。。。在无论如何,您可能需要在其他地方检查Reading a file line by line in Python。您不需要将整个文件读入列表。这对于大文件尤其不利。在
因为你只是在扫描名字,所以只需挑出每一行,不要像下面那样存储其余的。在
您还有一个随机的
pass
,它可能正在退出代码而不打印任何内容。所以事情确实会发生。。。你只是没印过别的东西。它鼓励你在学习调试的同时大量打印。在所以,我可以用字典来建议你这样做。在
如果多个名字出现在同一行,这也会计算在内。在
相关问题 更多 >
编程相关推荐