首页 > 解决方案 > 两个相同的程序有不同的结果。Python

问题描述

所以最近我学会了阅读文件并使用列表从它们中获取特定信息。今天,作为热身,我试图重建旧程序,但由于某种原因我无法得到正确的结果。我复制并粘贴了我制作的旧程序,仍然得到正确的结果。我想知道是否有人可以告诉我有什么区别,因为此时我已经完全复制了我的原始程序并且仍然可以获得正确的结果。

结果正确

fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
try:
    fh = open(fname)
except:
    print('File could not be opened',fname)
    quit()
count = 0
lst = list()
for line in fh:
    line = line.strip()
    lst = line.split()
    if not len(line) > 3: continue
    elif not line.startswith('From'): continue
    print(lst[1])
    count = count + 1

print("There were", count, "lines in the file with From as the first word")

正确结果:

fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
try:
    fh = open(fname)
except:
    print('Could not open file',fname)
    quit()
count = 0
lst = list()
for line in fh:
    line = line.strip()
    lst = line.split()
    if not len(lst) > 3: continue
    elif not line.startswith('From'): continue
    print(lst[1])
    count = count + 1

print("There were", count, "lines in the file with From as the first word")

它应该给我的结果是计数 27 和 27 个对应的电子邮件地址。这是有问题的文本文件。mbox-short 我正在使用 pycharm IDE

标签: pythonpython-3.x

解决方案


在第一个中,您正在检查“line”(if not len(line) > 3: continue)的长度,但在第二个中,您正在检查“lst”(if not len(lst) > 3: continue)的长度。那可能是你的问题。


推荐阅读