[英]SyntaxError: 'return' outside function generated in the comment
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))
上面的编码产生了语法错误,我在上面的标题中提到过。 有谁能帮助我解决这个问题? 感谢大家。
return语句应在函数/方法内使用。 您尚未定义一个,因此使用return
不正确。 您应该打印单词而不是使用return。 另外,您正在打开文件而不是关闭它。 我建议使用with
语句。
with open("output_log.text", "r") as myfile:
for file in myfile:
count = 0
for word in file:
if word == "Jenkins":
count = count + 1
print(int(word))
我很可能假设您正在尝试打印"Jenkins"
在文件中显示的次数。 您要打印count
。 另外, file
命名不当,因为您正在读取文件的行而不是文件的文件,所以它应为line
。 我想你正在做这样的事情
def count_word_in_file(filename, keyword):
count = 0
with open(filename, "r") as file:
for line in file:
for word in line.split():
if word == keyword:
count += 1
return count
count = count_word_in_file("output_log.text", "Jenkins")
print(count)
注意使用str.count
方法BTW可以更简单地完成此操作。
with open(filename, "r") as file:
print(file.read().count("Jenkins"))
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.