【问题标题】:Keyerror when searching through file with same strings.搜索具有相同字符串的文件时出现键错误。
【发布时间】:2015-08-26 13:17:14
【问题描述】:

您好,我在搜索具有多个序列号的大文件时遇到 KeyError。当我搜索文件并输入在文件中出现两次的序列号时,就会出现此问题。我想搜索这个文本文件并打印出我需要的序列号或用户输入。

这是错误:

    if item[param] != correct:
KeyError: 'APN'

这是我正在搜索的文件的文本示例:

500,SHOWALL
APN=" "
APU=" "
APP=" "
IPD="127.0.0.1"
DSP=1710
IPU="127.0.0.1"
VWD="2"

600,SHOWALL
APN=""
APU=" "
APP=" "
IPD="127.0.0.1"
DSP=1710
IPU="127.0.0.1"
VWD="2"

700,SHOWALL
APN=" "
APU=" "
APP=" "
IPD="127.0.0.1"
DSP=1710
IPU="127.0.0.1"
VWD="2"

500,SHOWALL
APN=""
APU=" "
APP=" "
IPD="127.0.0.1"
DSP=1710
IPU="127.0.0.1"
VWD="2"

由于 500 在文件中出现两次,它会遇到 KeyError。

这是我的代码示例:

def process(infile, outfile, keywords):

    keys = [[k[0], k[1], 0] for k in keywords ]
    endk = None
    with open(infile, "rb") as fdin:
        with open(outfile, "ab") as fdout:
            fdout.write("<" + words + ">" + "\n")
            for line in fdin:
                if endk is not None:
                    fdout.write(line)
                    if line.find(endk) >= 0:
                        fdout.write("\n")
                        endk = None
                else:
                    for k in keys:
                        index = line.find(k[0])
                        if index >= 0:
                            fdout.write(line[index + len(k[0]):].lstrip())
                            endk = k[1]
                            k[2] += 1
    if endk is not None:
        raise Exception(endk + " not found before end of file")
    return keys

这是我用于输入文件、输出文件和搜索文件的关键字的定义过程。这是代码的输出部分:

while (count < (len(setNames))):
    for number, item in enumerate(lst, 0):
        print setNames[count]
        for param, correct in correct_parameters.items():
            if item[param] != correct:
                print('{} = {} which is incorrect'.format(param, item[param]))
                with open(compareResults, "ab") as fdout:
                    fdout.write('{}'.format(setNames[count]) + " " + '{} = {} which is incorrect'.format(param, item[param])+ '\n')
        count += 1

如果序列号出现两次或更多,我的目标是如何让程序输出两次结果。因此,即使500 在我的文本文件中出现两次或更多次。我仍然希望它打印正确的所有 500 个结果。

这是我完整代码的链接。我没有发布完整的内容,因为它非常复杂,需要先清理一下。

http://pastebin.com/aCe9N8vW

如果需要更多信息,我会在下面发布。

【问题讨论】:

    标签: python string search keyerror


    【解决方案1】:

    听起来您没想到会发生 KeyError。如果是这种情况,那么使用item.get() 可能只会隐藏错误。考虑使用try/except

    try:
        if item[param] != correct:
            report_incorrect()
    except KeyError:
        print('Expected key {}'.format(param))
    

    确实,您应该返回代码并确定密钥不存在的原因。

    我试图查看您提供的链接,但代码还不够组织,我无法轻松阅读。这将有助于在顶部提供一些关于它应该做什么的 cmets。例如,

    """This code reads an input log file and a configuration file.
    For each serial number in the configuration file, it outputs how
    many times it occurs in the log file.
    """
    

    还有助于将更多的东西组织成函数,也许还有类,再一次用 cmets 来了解每个函数的目标。或许等代码清理干净,问题就迎刃而解了。

    【讨论】:

      【解决方案2】:

      你可以这样试试,

      if item.get(param) != correct:
      

      KeyError:

      Raised when a mapping (dictionary) key is not found in the set of existing keys.
      

      如果不想出现异常,可以使用get()方法

      【讨论】:

      • 效果很好。我有一个问题,为什么 item[param] 不起作用但 .get 方法起作用?我很困惑,因为密钥确实出现在现有的密钥集中,但只有在我搜索出现多次的字符串时才会出现此错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多