如果在要写入的文本文件中只执行了5行,我想执行一个循环。原因是,我希望从文本文件的最后5行计算平均值,如果程序没有5个数字可供使用,则会抛出一个rumtime错误。
#Imports
from bs4 import BeautifulSoup
from urllib import urlopen
import time
#Required Fields
pageCount = 1290429
#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0):
time.sleep(1)
html = urlopen('https://www.csgocrash.com/game/1/%s' % (pageCount)).read()
soup = BeautifulSoup(html, "html.parser")
try:
section = soup.find('div', {"class":"row panel radius"})
crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip()
logFile.write(crashPoint[0:-1]+"n")
except:
continue
for i, line in enumerate(logFile): #After 5 lines, execute this
if i > 4:
data = [float(line.rstrip()) for line in logFile]
print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))
else:
continue
print(crashPoint[0:-1])
pageCount+=1
logFile.close()
If anyone knows the solution, or knows a better way to go about doing this, it would be helpful, thanks :).
编辑:
更新代码:
#Imports
from bs4 import BeautifulSoup
from urllib import urlopen
import time
#Required Fields
pageCount = 1290429
lineCount = 0
def FindAverage():
with open('PastWinners.txt') as logFile:
data = [float(line.rstrip()) for line in logFile]
print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))
#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0):
time.sleep(1)
html = urlopen('https://www.csgocrash.com/game/1/%s' % (pageCount)).read()
soup = BeautifulSoup(html, "html.parser")
if lineCount > 4:
logFile.close()
FindAverage()
else:
continue
try:
section = soup.find('div', {"class":"row panel radius"})
crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip()
logFile.write(crashPoint[0:-1]+"n")
except:
continue
print(crashPoint[0:-1])
pageCount+=1
lineCount+=1
logFile.close()
新问题:程序按预期运行,但一旦计算并显示平均值,程序就不会再次循环,而是停止。我希望它能工作,所以在5行之后,它会计算平均值,然后显示下一个数字,然后显示新的平均值,以此类推
您的while
循环永远不会结束。我想你是想减少:pageCount-=1
。
最后的问题是循环没有重新启动,只是完成了第一次平均值计算。这是由于logFile被关闭而没有重新打开,所以程序考虑了这一点,并将其附加到文件中,它的工作与预期的一样。感谢大家的帮助。
#Imports
from bs4 import BeautifulSoup
from urllib import urlopen
import time
#Required Fields
pageCount = 1290429
lineCount = 0
def FindAverage():
with open('PastWinners.txt') as logFile:
data = [float(line.rstrip()) for line in logFile]
print("Average: " + "{0:0.2f}".format(sum(data[-5:])/len(data[-5:])))
#Loop
logFile = open("PastWinners.txt", "r+")
logFile.truncate()
while(pageCount>0):
time.sleep(1)
html = urlopen('https://www.csgocrash.com/game/1/%s' % (pageCount)).read()
soup = BeautifulSoup(html, "html.parser")
try:
section = soup.find('div', {"class":"row panel radius"})
crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip()
logFile.write(crashPoint[0:-1]+"n")
except:
continue
print(crashPoint[0:-1])
pageCount+=1
lineCount+=1
if lineCount > 4:
logFile.close()
FindAverage()
logFile = open("PastWinners.txt", "a+")
else:
continue
logFile.close()