gpt4 book ai didi

python - 如何在Python中获取循环范围内的值并在循环外使用它

转载 作者:行者123 更新时间:2023-11-30 23:50:22 24 4
gpt4 key购买 nike

有人可以帮助我思考解决这个问题的方法吗?在下面的代码中,我将获取一个列表并打开所有 .log 和 .txt 文件,以便在它们中搜索特定字符串。在最里面的 for 循环中有一个 if 和 else 语句,用于确定是否找到字符串。我想计算字符串匹配的文件数量...,并以某种方式将其传递给第三个(最后一个)for循环并显示...(例如匹配的文件:4)。我仍在学习 python,所以我不知道所有可以加快这一努力的不同结构。我确信这是一个直接的问题,但除了死记硬背的反复试验之外,我已经用尽了我所知道的一切。谢谢!

...

for afile in filelist:
(head, filename) = os.path.split(afile)
if afile.endswith(".log") or afile.endswith(".txt"):
f=ftp.open(afile, 'r')
for i, line in enumerate(f.readlines()):
result = regex.search(line)
if result:
ln = str(i)
pathname = os.path.join(afile)
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(ln, pathname, result.group())
hold = output
print output
ftp.get(afile, 'c:\\Extracted\\' + filename)
temp.write(output)
break
else:
print "String Not Found in: " + os.path.join(afile)
temp.write("\nString Not Found: " + os.path.join(afile))

f.close()
for fnum in filelist:
print "\nFiles Searched: ", len(filelist)
print "Files Matched: ", count
num = len(filelist)

temp.write("\n\nFiles Searched: " + '%s\n' % (num))
temp.write("Files Matched: ") # here is where I want to show the number of files matched
break

最佳答案

这个怎么样:

count = 0
for afile in filelist:
(head, filename) = os.path.split(afile)
if afile.endswith(".log") or afile.endswith(".txt"):
f=ftp.open(afile, 'r')
for i, line in enumerate(f.readlines()):
result = regex.search(line)
if result:
count += 1
ln = str(i)
pathname = os.path.join(afile)
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(ln, pathname, result.group())
hold = output
print output
ftp.get(afile, 'c:\\Extracted\\' + filename)
temp.write(output)
break
else:
print "String Not Found in: " + os.path.join(afile)
temp.write("\nString Not Found: " + os.path.join(afile))

f.close()
for fnum in filelist:
print "\nFiles Searched: ", len(filelist)
print "Files Matched: ", count
num = len(filelist)

temp.write("\n\nFiles Searched: " + '%s\n' % (num))
temp.write("Files Matched: "+str(count)) # here is where I want to show the number of files matched
break

计数从 0 开始,并随着每个匹配的文件而递增。

关于python - 如何在Python中获取循环范围内的值并在循环外使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7180119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com