【问题标题】:Python Name Error. Name is not defined while using Pandas dataframePython 名称错误。使用 Pandas 数据框时未定义名称
【发布时间】:2018-03-10 04:44:13
【问题描述】:

首先,我是 Python 新手。我正在尝试做的是从 CSV 中对我的数据进行词形还原。使用 pandas 读取 csv。 但是在运行此程序时,我在 lemmatized.append(temp) 行上遇到错误。它说 NameError: name 'temp' is not defined 我无法弄清楚是什么导致了这个错误。我正在使用python 2.7。 如果你们中的任何一位 python 专家可以帮助我解决这个简单的问题,从而帮助我学习,我将不胜感激。

data = pd.read_csv('TrainingSETNEGATIVE.csv')
list = data['text'].values


def get_pos_tag(tag):
    if tag.startswith('V'):
        return 'v'
    elif tag.startswith('N'):
        return 'n'
    elif tag.startswith('J'):
        return 'a'
    elif tag.startswith('R'):
        return 'r'
    else:
        return 'n'


lemmatizer = WordNetLemmatizer()
with open('new_file.csv', 'w+', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for doc in list:
        tok_doc = nltk.word_tokenize(doc)
        pos_tag_doc = nltk.pos_tag(tok_doc)
        lemmatized = []
        for i in range(len(tok_doc)):
            tag = get_pos_tag(pos_tag_doc[i][1])
            if tag == 'r':
                if tok_doc[i].endswith('ly'):
                    temp = tok_doc[i].replace("ly", "")
            else:
                temp = lemmatizer.lemmatize(tok_doc[i], pos=tag)
            lemmatized.append(temp)
        lemmatized = " ".join(lemmatized)
        wr.writerow([lemmatized])
        print(lemmatized)

截图:

【问题讨论】:

  • 如果 tag == 'r' 返回 True,但 tok_doc[i].endswith('ly') 返回 False,则永远不会定义 temp。我怀疑这就是导致错误的原因。
  • 是的,这就是原因。非常感谢你

标签: python python-2.7 lemmatization


【解决方案1】:

异常说明了一切:“名称'temp'未定义”。所以变量temp在使用前没有定义。

你的代码有问题:

if tag == 'r':
    if tok_doc[i].endswith('ly'):
        temp = tok_doc[i].replace("ly", "")
    # else: temp = None
else:
    temp = lemmatizer.lemmatize(tok_doc[i], pos=tag)
lemmatized.append(temp)

如果 tag == 'r' 为 True 且 tok_doc[i].endswith('ly') 不是 True,则永远不会定义 temp

考虑添加一个else 子句,就像我插入并注释掉的那个子句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2022-01-01
    • 2019-11-13
    相关资源
    最近更新 更多