首页 > 解决方案 > SyntaxError: 'return' 在注释中生成的外部函数

问题描述

myfile=open("output_log.text", "r")
for file in myfile:
    count = 0
    for word in file:
        if word == "Jenkins":
            count = count + 1
        return word
print(int(word))

上面的编码产生了我在上面的标题中提到的语法错误。有谁可以帮我解决这个问题?感谢大家。

标签: python

解决方案


OK, you have not defined a function yet. :-)  

####### Beginning of python script #######

def myfunc(myword, myfile):
    # rest of your function code.
    for file in myfile:
        count = 0
        for word in file:
            if word == myword:
                count = count + 1
    return myword, count  

# Now call the function from outside.
# Set myfile and myword variables.
myfile = open(r'c:\python\so\output_log.text', "r")
myword = 'Jenkins'
results = myfunc(myword, myfile)

print(results)
# Example print output.
> ('Jenkins', 4) 

# You are passing myfile and myword as variables in your function call.
# You can changes these later for a different file and a different word.

推荐阅读