def to_brower_file(cls, arg, file=None, clsmsg=True, to_html_args=None): """ 将任意数值类型的arg转存到文件,转换风格会尽量适配浏览器的使用 :param arg: 任意类型的一个数据 :param file: 想要存储的文件名,没有输入的时候会默认生成到临时文件夹,文件名使用哈希值避重 :param clsmsg: 显示开头一段类型继承关系、对象占用空间的信息 :param to_html_args: df.to_html相关格式参数,写成字典的形式输入,常用的参数有如下 escape, 默认True,将内容转移明文显示;可以设为False,这样在df存储的链接等html语法会起作用 说明:其实所谓的用更适合浏览器的方式查看,在我目前的算法版本里,就是尽可能把数据转成DataFrame表格 """ # 1 如果已经是文件、url,则不处理 if is_file(arg) or is_url(arg) or isinstance(arg, File): return arg # 2 如果是其他类型,则先转成文件,再打开 arg_ = TypeConvert.try2df(arg) if isinstance(arg_, pd.DataFrame): # DataFrame在网页上有更合适的显示效果 if clsmsg: t = f'==== 类继承关系:{inspect.getmro(type(arg))},' \ + f'内存消耗:{sys.getsizeof(arg)}(递归子类总大小:{getasizeof(arg)})Byte ====' content = '<p>' + html.escape(t) + '</p>' else: content = '' # TODO 把标题栏改成蓝色~~ content += arg_.to_html(**(to_html_args or {})) if file is None: file = File(..., Dir.TEMP, suffix='.html').write(content) file = file.rename(get_etag(str(file)) + '.html', if_exists='replace') else: file = File(file).write(content) elif getattr(arg, 'render', None): # pyecharts 等表格对象,可以用render生成html表格显示 try: name = arg.options['title'][0]['text'] except (LookupError, TypeError): name = datetime.datetime.now().strftime('%H%M%S_%f') if file is None: file = File(name, Dir.TEMP, suffix='.html').to_str() arg.render(path=str(file)) else: # 不在预设格式里的数据,转成普通的txt查看 if file is None: file = File(..., Dir.TEMP, suffix='.txt').write(arg) file = file.rename(get_etag(str(file)) + file.suffix, if_exists='replace') else: file = File(file).write(arg) return file
def writefile(ob, path='', *, encoding='utf8', if_exists='backup', suffix=None, root=None, etag=None) -> str: """往文件path写入ob内容 :param ob: 写入的内容 如果要写txt文本文件且ob不是文本对象,只会进行简单的字符串化 :param path: 写入的文件名,使用空字符串时,会使用etag值 :param encoding: 强制写入的编码 :param if_exists: 如果文件已存在,要进行的操作 :param suffix: 文件扩展名 以'.'为开头,设置“候补扩展名”,即只在fn没有指明扩展名时,会采用 :param root: 相对位置 :return: 返回写入的文件名,这个主要是在写临时文件时有用 """ if etag is None: etag = (not path) if path == '': path = ... f = File(path, root, suffix=suffix).write(ob, encoding=encoding, if_exists=if_exists) if etag: f = f.rename(get_etag(str(f))) return str(f)
def html(self, arg, **kwargs): """ 将内容转为html展示 """ file = File(..., Dir.TEMP, suffix='.html').write(arg) file = file.rename(get_etag(str(file)) + file.suffix, if_exists='replace') self.__call__(arg, file, **kwargs)