我编写了一个生成随机坐标并将它们写入没有格式的文本文件的脚本。
有没有一种方法可以格式化此列表以使其更易于阅读?像 (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()
我试过拆分,但没有用。我知道我不需要线程选项。我宁愿在范围内进行线程化,但目前范围还可以...
Example of the text in text file: [4308][1461][1163][846][1532][318]... and so on
我写了一个 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()
请您参考如下方法:
为了让你的绘图逻辑正常工作,文件应该这样写
with open('new.txt', 'w') as out_file:
for count in range(12000):
x = random.randint(0,10000)
y = random.randint(0,10000)
outfile.write("{},{}\n".format(x, y))
还有,你读这样的行
def animate(i):
xs = []
ys = []
with open('filename') as graph_data:
for line in graph_data:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs,ys)
