无法从线路获取输出

发布于 2025-01-13 04:46:05 字数 1159 浏览 2 评论 0原文

我一直在努力获取该行的输出,刚刚开始在 coursera 上学习 python,并且一直坚持这个练习。

fname = input("Enter file name: ")
fh = open(fname)
count = 0
total = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    else :
        x = line.find(':')
        y = line.find(' ',x)
        z = line.find(' ',y)
        num = line[y+1:z]
        azz = float(num)
        total = total + azz
        count = count + 1

print(azz)
print("Done")

由于某种原因,我无法打印 azz 或 num。 我确实想出了一个不同的解决方案,如下所示:

fname = input("Enter file name: ")
fh = open(fname)
count = 0
total = 0 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    else :  
        x = line.find(' ')
        y = line.find(' ',x)
        num = line[x+1:]
        azz=float(num)
        count = count + 1
        total = total + azz
                
        
print(azz)

现在它可以工作了。我不明白为什么给出结束索引会造成这个问题。 在这种情况下 num = line[x+1:] 不会产生任何问题,因为数字后面的同一行上没有任何内容,但是如果之后在同一行上写了一些内容,则不会产生任何问题这是一个问题吗?(因为我只想提取浮点) 或者它没有给我一个数字的原因是因为在同一行的数字后面没有写任何内容,并且给它一个结束索引对Python来说没有意义? 我希望我很好地表达了我的问题。 在第一个版本中,它给了我 NaN(不是数字错误)

I have been struggling to get the output from the line, just starting to learn python on coursera and have been stuck on this exercise.

fname = input("Enter file name: ")
fh = open(fname)
count = 0
total = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    else :
        x = line.find(':')
        y = line.find(' ',x)
        z = line.find(' ',y)
        num = line[y+1:z]
        azz = float(num)
        total = total + azz
        count = count + 1

print(azz)
print("Done")

for some reason I can't print azz or num.
I did come up with a different solution which looks like this:

fname = input("Enter file name: ")
fh = open(fname)
count = 0
total = 0 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    else :  
        x = line.find(' ')
        y = line.find(' ',x)
        num = line[x+1:]
        azz=float(num)
        count = count + 1
        total = total + azz
                
        
print(azz)

And now it works. I can't figure out why giving ending index is making this problem.
In this case
num = line[x+1:] doesn't create any issue because there is not anything on the same line after numbers, however if there was some things written on the same line after that wouldn't it be a problem?(because I only wanted to extract floating points)
Or the reason it wasn't giving me a number was because there was nothing written after number on the same line and giving it an end index wasn't making sense to python?
I hope I articulated my question well.
In the first version it was giving me NaN(not a number error)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文