<p>可以使用<a href="https://docs.python.org/2/library/fileinput.html" rel="nofollow noreferrer">fileinput</a>模块读取文本文件,并使用<a href="http://matplotlib.org/" rel="nofollow noreferrer">matplotlib</a>模块绘制所需的图形。更多细节可以在下面的代码中看到。你知道吗</p>
<pre><code>import fileinput
temp_values = []
for line in fileinput.input("weerstation.txt"):
print line, type(line)
if 'temperatuur' in line:
temp_values.append(line.strip().split()[1]) # split the list and just add the temperature
with open("temp_values.txt", "w") as fp:
fp.write("\n".join(temp_values)) # save values to temp_values.txt and finish assignment 1
print temp_values
# ['10.4', '10.9', '10.9', '10.9', '11.0', '11.1', '11.3', '11.4', '11.5', '11.5', '12.0', '12.5', '13.0', '13.5', '13.5', '12.5', '10.5', '9.5', '9.0', '9.0', '8.5', '8.25', '7.0', '5.0']
import matplotlib.pyplot as plt # using matplotlib to draw figure and finish assignment 2
plt.plot([i for i in xrange(0, 24)], temp_values)
plt.xlabel("Hours")
plt.ylabel("Temperatures")
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/YIyLE.png" alt="enter image description here"/></p>