SageMath中_read_planar_code读取平面码文件的方法问询
关于SageMath中
_read_planar_code读取平面码文件的问题 问题描述
平面码是一种存储平面图的格式,我尝试用SageMath的_read_planar_code函数读取包含多个图的平面码文件,但直接传入文件名时触发错误。
尝试的代码及报错
执行以下代码:
s=graphs._read_planar_code("triangulations_10.pl") s next(s)
得到生成器对象,但调用next(s)时出现错误:
AttributeError: 'str' object has no attribute 'read'
错误原因是_read_planar_code函数的参数需要的是可读取的文件对象,而非字符串格式的文件名。
实际需求
需要迭代读取平面码文件中的每个图,筛选出符合特定属性(例如完美图)的图,类似以下graph6格式的读取逻辑:
with open('planar_conn.7.g6', 'r') as file: for line in file: graph6_string = line.strip() graph = Graph(graph6_string) if graph.is_perfect(): graph.show() break
正确实现方式
将打开的文件对象传入_read_planar_code,即可迭代生成图对象,示例代码如下:
with open('triangulations_10.pl', 'rb') as file: # _read_planar_code处理二进制文件,所以用rb模式打开 for graph in graphs._read_planar_code(file): if graph.is_perfect(): graph.show() break
注意:平面码文件需要以二进制模式(rb)打开,因为函数内部会按字节读取头部验证信息。
内容的提问来源于stack exchange,提问作者licheng
相关产品推荐
相关产品推荐

