我正在通过一个程序来获取用户的.txt文件,该文件一次处理3行:第一行是X坐标,第二行是y坐标。第三行是样式。 (用户可以根据需要输入3行的许多不同部分。该程序将通过从lines[0]-line[2]
进行处理并打印相应的图形,然后lines[3]-line[5]
进行操作,并不断进行直到完成到达终点。
一张图的示例:
2 4 6
1 2 3
--r
我已经建立了基金会。但是,当我尝试将第三行实现到plt.plot()中时,由于无法识别的错误,程序崩溃了:
'Unrecognized character %c in format string' % c)
(底部的完整回溯)
ValueError:无法识别的字符 格式字符串。 请参阅下面的代码:
import matplotlib.pyplot as plt
with open("testfile.txt") as f:
lines = list(f)
x_components = list(map(int, lines[0].split()))
y_components = list(map(int, lines[1].split()))
style = lines[2]
line_to_string = "".join(map(str, style))
plt.plot(x_components, y_components, line_to_string)
非常感谢您的帮助。
跟踪:
Traceback (most recent call last):
Traceback (most recent call last):
File "plots.py", line 11, in <module>
plt.plot(x_components, y_components, line_to_string)
File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2795, in plot
is not None else {}), **kwargs)
File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py", line 1666, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 225, in __call__
yield from self._plot_args(this, kwargs)
File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 366, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 106, in _process_plot_format
'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character
in format string
>
.txt文件的屏幕截图如下:
答案 0 :(得分:0)
尝试从此行-style = lines[2]
进行调试。
line_to_string
可以包含'\n'
或其他内容
答案 1 :(得分:0)
您应从格式字符串的末尾删除换行符:
with open("testfile.txt") as f:
lines = f.readlines()
x_components = list(map(int, lines[0].split()))
y_components = list(map(int, lines[1].split()))
style = lines[2].strip()
line_to_string = "".join(map(str, style))
plt.plot(x_components, y_components, line_to_string)
顺便说一句,如果您不检查格式字符串是否有效,则该方法很脆弱。