Python名称错误。使用Pandas数据帧时未定义名称

时间:2018-03-10 04:44:13

标签: python python-2.7 lemmatization

首先,我是Python的新手。我想要做的是从CSV中将我的数据变为lemmatize。用过的pandas来读取csv。 但是在运行这个时,我在行lemmatized.append( temp )上收到错误。它是说 NameError:名称'temp'未定义 我无法弄清楚导致此错误的原因。我正在使用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)

Screentshot: enter image description here

1 个答案:

答案 0 :(得分:4)

Exception说明了一切:“名称'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子句,就像我插入并注释掉的那样。