python - 两个相同的程序有不同的结果。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
解决方案
在第一个中,您正在检查“line”(if not len(line) > 3: continue
)的长度,但在第二个中,您正在检查“lst”(if not len(lst) > 3: continue
)的长度。那可能是你的问题。
推荐阅读
- angular - 从没有 id 的 ngrx 实体中选择单例实体
- mongodb - Docker Swarm MongoDB:initAndListen 中的异常:DBPathInUse
- java - BasicDynaBean从java中的postgres查询返回嵌套的空行
- powershell - 动态参数开关读起来不像静态参数 [开关]?
- python - TypeError: 'JpegImageFile' 和 'JpegImageFile' 的实例之间不支持'<' 排序列表时出错
- reactjs - 在 react native 应用程序中使用多个 redux 商店以获取不同的版本
- vue.js - 在单个 vuejs 应用程序中单独设计 Web 和电子应用程序
- gitlab - CI Build 不上传工件
- r - 在 ubuntu 18.04 上使用 conda 将 R 4.0.5 更新到 R 4.1.1
- html - 如何将css文件添加到cshtml文件中?