【发布时间】:2017-06-08 12:21:47
【问题描述】:
我编写了一个脚本,它生成随机坐标并将它们写入一个没有格式的文本文件。
有没有办法格式化这个列表以便于阅读?就像每行(x,y)一样?现在它是一个列表,它们之间有一个空格。
有没有一种更简单的方法可以在不使用文本文件的情况下在一个 python 文件中生成随机坐标?还是使用文本文件更容易?
下面是这个的工作代码和一个文本文件的例子:(根据评论和工作修订)
import random
import threading
def main():
#Open a file named numbersmake.txt.
outfile = open('new.txt', 'w')
for count in range(12000):
x = random.randint(0,10000)
y = random.randint(0,10000)
outfile.write("{},{}\n".format(x, y))
#Close the file.
outfile.close()
print('The data is now the the new.txt file')
def coordinate():
threading.Timer(0.0000000000001, coordinate).start ()
coordinate()
#Call the main function
main()
我尝试过拆分,但不起作用。我知道我不需要线程选项。我宁愿在范围内进行线程处理,但范围现在还可以......
文本文件中的文本示例: [4308][1461][1163][846][1532][318]...等等
我编写了一个 python 脚本,它读取坐标的文本文件并将它们放在图表上,但是没有绘制任何点。图表本身确实显示。下面是代码:(根据评论修改)
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from numpy import loadtxt
style.use('dark_background')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
with open('new.txt') as graph_data:
for line in graph_data:
x, y = line.split(',')
def animate(i):
xs = []
ys = []
for line in graph_data:
if len(line)>1:
x,y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs,ys)
lines = loadtxt("C:\\Users\\591756\\new.txt", comments="#", delimiter=",", unpack="false")
ani = animation.FuncAnimation(fig, animate, interval=1000) # 1 second- 10000 milliseconds
plt.show()
【问题讨论】:
-
您必须手动将换行符写入文件或任何其他分隔符。但是,pickle 或 json 模块会是更好的方法
-
可能没有绘制点,因为
split(',')在数据中没有逗号就无法工作? -
太棒了!文本文件看起来很漂亮。非常感谢你的帮助!我已完成所有编辑并添加到提取值的脚本中,但是,我刚刚收到一条错误消息,指出“ValueError: I/O operation on closed file.”
-
如果使用with open语法,则不需要手动关闭文件
-
我已经更新了上面的文本以显示修改后的代码。仍然不能使用“with open”语法。我还需要“def animate”中的“for”语句吗?
标签: python python-3.x animation graph real-time