在具有相同字符串的文件中搜索时出现Keyerror。

2024-04-28 15:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有一个键错误时,通过一个巨大的文件搜索多个序列号。当我搜索文件并输入一个在文件中出现两次的序列号时,就会出现这个问题。我想搜索这个文本文件并打印出我需要的序列号或用户输入。你知道吗

这是错误:

    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

如果需要更多的信息,我会在下面发布。你知道吗


Tags: 文件inforifparamlineitemwrite
2条回答

听起来好像你没料到会发生KeyError。如果是这样,那么使用item.get()可能只会隐藏错误。考虑使用try/except

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

实际上,您应该返回代码并确定密钥不存在的原因。你知道吗

我试图看看你提供的链接,但代码还没有组织足够我容易阅读。它将有助于在顶部提供一些关于它应该做什么的评论。例如

"""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.
"""

此外,它还将有助于将更多的东西组织到函数中,也许还可以组织到类中,并对每个函数的目标进行注释。也许当代码被清除后,问题就会消失。

你可以这样试试

if item.get(param) != correct:

键错误:

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

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

相关问题 更多 >