zoukankan      html  css  js  c++  java
  • dbfread报错ValueError错误解决方法

    问题

    我在用dbfread处理.dbf数据的时候出现了报错

    ValueError("could not convert string to float: b'.'",)

    然后查找.dbf源文件的时候,发现在报错的那一行数据中,有一列甚至好几列的数据中出现了'.',里面是否有空格忘记了,但是应该没关系,我查阅了dbfred库文件中的代码,里面对空格的问题已经有了很好的处理。所以这里报错的原因就是

    string类型的'.'被认为是数值,却无法转换为float类型的数值,导致报错。

    原因

    点击报错的位置,错误信息里面除了有代码中出错的位置之外,还有库文件中出错的位置。

    点击之后就可以看到,在文件dbfread/field_parser.py中

    def parseN(self, field, data):
        """Parse numeric field (N)
    
        Returns int, float or None if the field is empty.
        """
        # In some files * is used for padding.
        data = data.strip().strip(b'*')
    
        try:
            return int(data)
        except ValueError:
            if not data.strip():
                return None
            else:
                # Account for , in numeric fields
                return float(data.replace(b',', b'.'))

    可见在源码中没有对'.'进行处理就

    return float(data.replace(b',', b'.'))

    解决方案

    知道了原因之后,我们就只需要增加一个elif来对'.'进行处理就好了。

    def parseN(self, field, data):
        """Parse numeric field (N)
        Returns int, float or None if the field is empty.
        """
        # In some files * is used for padding.
        data = data.strip().strip(b'*')
        try:
            return int(data)
        except ValueError:
            if not data.strip():
                return None
    
            # For English: If the value is b'.', we need return '.', or the code will have some error.
            # For Chinese: 在我的代码中,有的值是'.',然后运行了之后就报了格式错误,添加下面两行代码可以解决这个问题,返回值是String类型的'.'
            elif data.strip() == b'.':
                return '.'
    
            else:
                # Account for , in numeric fields
                return float(data.replace(b',', b'.'))

    在里面加入了两行代码

    elif data.strip() == b'.':

        return '.'

    详情可见我在github上对修改

    https://github.com/TinyHandsome/dbfread.git

    展望

    我想除了'.'的问题之外,可能还会有各种奇葩的问题,同样可以通过修改库文件的方法,直接将无法处理的字符串或信息,转换成你想要得到的信息,比如我这里是"."到".",虽然都是“.”,但是结果完全不一样,至少不会报错,对于问题的解决也挺直接的。

    希望能解决读者的问题。有其他的问题可以通过回复或者私聊我。

  • 相关阅读:
    Study Plan The TwentySecond Day
    Study Plan The Nineteenth Day
    Study Plan The TwentySeventh Day
    Study Plan The Twentieth Day
    Study Plan The TwentyFirst Day
    python实现进程的三种方式及其区别
    yum makecache
    JSONPath 表达式的使用
    oracle执行cmd的实现方法
    php daodb插入、更新与删除数据
  • 原文地址:https://www.cnblogs.com/lyjun/p/10281898.html
Copyright © 2011-2022 走看看