【问题标题】:Extract certain values from multiple lines from a txt file从 txt 文件的多行中提取某些值
【发布时间】:2020-07-16 17:03:06
【问题描述】:

之前有人提出并回答了类似的问题,但我想知道为什么我的代码没有产生正确的输出。

我的 txt 文件中有几行如下所示:X-DSPAM-Confidence: 0.xxxx

0.xxxx 值会有所不同。我需要从每个“X-DSPAM-Confidence:”行中切出该部分并计算平均值。

txt文件可以在这里下载:http://www.py4e.com/code3/mbox-short.txt

我的代码如下:

fname = input("Enter file name: ")
fh = open(fname)
count = 0
current = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue   # Please do not change this line and develop the program based on it
    count = count + 1  # I think this would count how many lines that starts with X-DSPAM-Confidence:
    pos = line.find(':')    # This should find me the position for ":"
    number = line[pos+5:]   # I think this should slice the number out
    final = float(number) + current    # Then I float the number and add to the current running number
print("Average spam confidence: ", final/count)    # Finally, when the loop finishes with the file, print the average

使用上面的代码,我得到了平均 33.5925925926,但正确答案应该是 0.750718518519。

谁能赐教?

【问题讨论】:

  • 你永远不要重复使用final,最后做current= float(number) + currentcurrent/count

标签: python string parsing split


【解决方案1】:

根据您的要求,进行最小但基本的更改。

    fname = input("Enter file name: ")
    with open(fname, "r") as current_file: 
        # i can not stress enough the importance of the with method over 
        #open()/close()
            content = current_file.readlines()

    count = 0
    current = 0
    for line in content:
        if not line.startswith("X-DSPAM-Confidence:"): continue
        count = count + 1  
        pos = line.find(':')    
        number = line[pos+2:]   # small error, it was not 5 but 2 instead
        current = float(number) + current
    print("Average spam confidence: ", current/count)

【讨论】:

  • 嗨 - 感谢您的代码。我实际上正在上在线课程。我还没有学到那么多。您是否可以尽可能少地更改我的代码以获得所需的输出?
  • @LeonC 这是代码。我希望它能满足您的要求
  • 非常感谢。有效!我已经坚持了8个小时。我需要用 open() 和 content = current_file.readlines() 研究你的开始部分。我还没学过。
  • 我可以知道为什么它是 pos+2 吗?我有一个更简单的练习,我需要将值从“X-DSPAM-Confidence:0.8475”这一行中剔除。在这个练习中,我提取了位置 [23:29] 并且它起作用了。我从 X 作为位置 0 开始,将每个字母和小空格一个一个地数了一遍。我认为数字 0.8475 之前有 4 个小空格。但似乎通过 pos +2 整个空格都被视为 1。
  • 刚发现pos+1、+2、+3都有效。从+4开始会有问题
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多