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))
上面的编码产生了语法错误,我在上面的标题中提到过。有谁能帮助我解决这个问题?感谢大家。
答案 0 :(得分:0)
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)
方法BTW来轻松完成此操作。
str.count
答案 1 :(得分:0)
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.