【问题标题】:python udf error in pig猪中的python udf错误
【发布时间】:2015-03-03 04:13:07
【问题描述】:

我正在尝试在 Pig 中的 python udf 下运行

@outputSchema("word:chararray")
def get(s):
    out = s.lower()
    return out;

我遇到以下错误:

  File "/home/test.py", line 3, in get
    out = s.lower()
AttributeError: 'NoneType' object has no attribute 'lower'

【问题讨论】:

    标签: python apache-pig


    【解决方案1】:

    s 为none 时,您应该处理这种情况。在大部分examples such as

    from pig_util import outputSchema
    
    @outputSchema('decade:chararray')
    def decade(year):
        """
        Get the decade, given a year.
    
        e.g. for 1998 -> '1990s'
        """
        try:
            base_decade_year = int(year) - (int(year) % 10)
            decade_str = '%ss' % base_decade_year
            print 'input year: %s, decade: %s' % (year, decade_str)
            return decade_str
        except ValueError:
            return None
    

    值为None时需要处理。因此,一种可能的解决方法是尝试:

    @outputSchema("word:chararray")
    def get(s):
        if s is None:
            return None
        return str(s).lower()
    

    【讨论】:

    • 有人甚至会争辩说,如果你想调用lower(),你应该确保你正在处理一个字符串。所以也许像str(s).lower() 这样的东西会更安全。如果输入为 None,我个人更喜欢 None 作为返回值而不是空字符串,但根据数据/预期结果,即使失败也是一种选择(在调用 UDF 之前可以过滤掉 None)。
    • 好答案,但值得注意的是,最新版本的 python 不支持此示例的字符串格式(请参阅此处的discussion。)
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多