【问题标题】:Python: Unresolved reference in try catchPython:try catch 中未解决的引用
【发布时间】:2020-01-18 15:01:53
【问题描述】:

我正在尝试在 except/else 中使用累加器(变量):

更新代码

classifier = UtteranceClassifier()

sc = SparkContext("local[2]")

offensives = sc.accumulator(0)
total = sc.accumulator(0)

# Create Spark session
def get_spark_session():
    return SparkSession \
        .builder \
        .master(master) \
        .appName(appName) \
        .getOrCreate()


def classify(utterance):
    global offensives
    global total

    total += 1
    print("total: ", total)
    try:
        return classifier.classify(utterance)
    except Exception:
        offensives += 1
        print("offensives: ", offensives)



def main():
    spark: SparkSession = get_spark_session()

    ....

    # Clean text
    df_clean = df.select((f.lower(f.regexp_replace('utterance', "[^a-zA-Z\\s]", "")).alias('utterance_text')))

    # Tokenize text
    tokenizer = Tokenizer(inputCol='utterance_text', outputCol='utterance_token')
    df_words_token = tokenizer.transform(df_clean).select('utterance_token')

    # Remove stop words
    remover = StopWordsRemover(inputCol='utterance_token', outputCol='utterance_clean')
    df_no_stopwords = remover.transform(df_words_token).select('utterance_clean')
    #df_no_stopwords.show(truncate=False)

    classify_udf = f.udf(classify, StringType())
    # Classify utterance
    df_no_stopwords = df_no_stopwords.withColumn("offensive", classify_udf(f.col('utterance_clean')))
    df_no_stopwords.show(truncate=False)

    print("Offensives: ", offensives.value)
    print("Total: ", total.value)

我对变量总数和进攻性都有这样的编译错误:

检查信息:此检查检测到应该解析但不...

【问题讨论】:

  • 请贴出实际代码而不仅仅是图片
  • 无图像:将您的代码和相关错误发布为文本
  • 看来您正试图在python 中进行c 编程。没有像num_of_offensive++total++ 这样的语法。存在于python中。
  • 如果我使用相同:num_of_offensive=num_of_offensive+1 !!
  • 变量范围有问题。

标签: python python-3.x pyspark


【解决方案1】:

Python 没有++ 运算符。你可以用+= 运算符代替:

def classify(utterance):
    try:
        classifier.classify(utterance)
    except Exception:
        num_of_offensive += 1
    else:
        total += 1

【讨论】:

  • 即使使用 +=,这些变量上仍然存在相同的错误“未解析的引用”
  • @zbeedatm 请分享您在更新代码后遇到的确切错误
  • 编译错误:检查信息:此检查检测到应该解析但没有解析的名称
  • 如果你设置total = total + 1(或total += 1),你会创建一个局部变量total(准确地说:你将局部名称total绑定到total + 1的结果)。现在 Python 知道 total 是一个局部变量,并试图在 total + 1 中使用它。但是你从来没有定义一个局部变量total ans 所以你得到一个错误。修复:如果您在外部范围中有total,则将其作为参数传入并返回新的总数。这同样适用于num_of_offensive
  • 恐怕我做不到,因为它是一个Spark累加器,并且在出现异常时增加它的整个想法。我将使用在数据帧上调用此方法的行更新我的代码
【解决方案2】:

您将 if/else 与 try/except 混淆了。这样做:

    def classify(utterance):
        try:
            classifier.classify(utterance)
            total += 1
        except:
            num_of_offensive += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 2016-10-12
    • 1970-01-01
    • 2018-01-23
    • 2021-10-03
    • 2011-07-10
    • 1970-01-01
    • 2013-07-26
    相关资源
    最近更新 更多