2016-12-16 70 views
-1
for x in non_neutral.collect(): 
tweet = str(x[2]) 
sid = x[1] 
status = x[0] 
text = word_tokenize(tweet) 
text1 = list(text) 
tweet = x[2].split() 
pronoun = intersect(second_pronoun,tweet) 
perojective = intersect(less_offensive,tweet) 
if pronoun: 
    pronoun_index = tweet.index(pronoun[0]) 
    pero_index = tweet.index(perojective[0]) 
if pero_index <= pronoun_index+3: 
    status = 1 
    return Row(status=status,tid=sid,tweet = str(tweet)) 
else: 
    status = 0 
    return Row(status=status,tid=sid,tweet = str(tweet)) 

返回的代码,我经常收到这个错误,这个特殊的代码片段,我不明白为什么的Python:外功能错误

File "<ipython-input-5-0484b7e6e4fa>", line 15 
return Row(status=status,tid=sid,tweet = str(tweet)) 
SyntaxError: 'return' outside function 

我试图重新编写代码,但仍然得到同样的错误。

+2

你的问题肯定是由于缩进。我认为在这里比在实际问题中更加错误 –

+2

除了缩进之外,您还有返回语句,但没有函数定义。你有一个def funcname(输入):? – Kelvin

+0

那么,你有一个函数外的'return'。什么让人困惑? –

回答

1

我在代码片段中看不到关键字def,这将指示函数定义的开始。这个片段是从一个函数的主体中获取的吗?

这是在返回for循环的工作示例:

from random import shuffle 

def loop_return(): 
    values = [0,1] 
    shuffle(values) 
    for i in values: 
     if i == 0: 
      return 'Zero first.' 
     if i == 1: 
      return 'One first.' 
+0

是的!我已经把这个片段用于测试。但它在for循环。那么在循环中有return语句是不是正确? – nile

+0

return语句的唯一要求是它必须存在于函数体中。我怀疑你的代码有一些语法错误,Python解释器不能识别函数定义的开始。我在for循环中添加了一个返回样本以供我回答。 – Apollo2020

3

你的程序实际上并不包含一个函数。返回语句必须包含在一个函数中,在这种情况下你还没有定义任何函数。

尝试更多的东西像下面的(注意,这并不包括所有的代码,这只是一个例子):

def Foo(): 
    #Here is where you put all of your code 
    #Since it is now in a function a value can be returned from it 
    if pronoun: 
     pronoun_index = tweet.index(pronoun[0]) 
     pero_index = tweet.index(perojective[0]) 
    if pero_index <= pronoun_index+3: 
     status = 1 
     return Row(status=status,tid=sid,tweet = str(tweet)) 
    else: 
     status = 0 
     return Row(status=status,tid=sid,tweet = str(tweet)) 

Foo() 

只要你把你的代码的功能,将工作。 python中基本函数定义的语法是:def Foo(Bar):其中Foo是函数的名称,Bar是您可能需要的任何参数,每个参数都用逗号分隔。

1

你实际上没有一个函数,所以你不能返回任何东西。你可以通过使代码成为一个过程来修复它。