titles.map(item => ({title: item}))

本文介绍了一个使用JavaScript将数组元素转换为对象数组的例子。通过`map`函数遍历字符串数组,构造出具有`name`属性的对象数组,并展示了如何利用`console.log`输出最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   <script>
        var titles=['kity','xiaohua','caimiao']
        const vtabs = titles.map(item => ({'name': item}))
        console.log(vtabs);
        // [ {name: "kity"}, {name: "xiaohua"},{name: "caimiao"}]
    </script>
<!DOCTYPE html> <html lang="zh-Hans"> <head itemprop="video" itemscope itemtype="http://schema.org/VideoObject"> <meta name="format-detection" content="telephone=no, email=no"> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <meta name="spm_prefix" content="333.788"> <meta name="referrer" content="no-referrer-when-downgrade"> <meta name="applicable-device" content="pc"> <meta http-equiv="Cache-Control" content="no-transform"> <meta http-equiv="Cache-Control" content="no-siteapp"> <link rel="shortcut icon" href="https://i0.hdslb.com/bfs/static/jinkela/long/images/favicon.ico"> <link rel="stylesheet" href="//s1.hdslb.com/bfs/static/jinkela/long/font/regular.css" media="all"> <link rel="stylesheet" href="//s1.hdslb.com/bfs/static/jinkela/long/font/medium.css" media="all"> <link rel='preload' href='//s1.hdslb.com/bfs/static/player/main/core.42bf7afe.js' as='script'/> <link rel="stylesheet" href="//s1.hdslb.com/bfs/seed/jinkela/short/bili-theme/map.css"/> <link rel="stylesheet" href="//s1.hdslb.com/bfs/seed/jinkela/short/bili-theme/light_u.css"/> <link id="__css-map__" rel="stylesheet" href="//s1.hdslb.com/bfs/seed/jinkela/short/bili-theme/light.css"/> <script type="text/javascript"> window.webAbTest = { "login_dialog_version": "V0", "abr_limit_version": "V_PLAYER_ABR_LIMIT", "ai_summary_version": "SHOW", "bmg_fallback_version": "DEFAULT", "rcmd_tab_version": "DISABLE", "comment_version_hash": "8d14695d99", "in_new_ab": true, "ab_version": { "login_dialog_version": "V0", "abr_limit_version": "V_PLAYER_ABR_LIMIT", "ai_summary_version": "SHOW", "bmg_fallback_version": "DEFAULT", "rcmd_tab_versio
03-19
import os import re import shutil import zipfile import tempfile from typing import List, Dict, Tuple import tkinter as tk from tkinter import filedialog, messagebox from docx import Document from docx.shared import Pt from docx.oxml import parse_xml from docx.oxml.ns import nsdecls, qn from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml.shape import CT_Picture from docx.oxml.table import CT_Tbl from docx.oxml.text.paragraph import CT_P class WordProcessor: def __init__(self): self.input_path = "" self.output_dir = "" self.full_titles = [] self.current_title_path = [] self.ignore_titles = ["目录", "目 录", "contents", "Contents"] self.chapter_counter = 0 self.image_counter = 1 self.media_files = {} # 存储图片文件 self.base_filename = "" # 基础文件名 self.source_doc = None # 存储原始文档对象 def select_input_file(self): """选择输入文件""" root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( title="选择要处理的Word文档", filetypes=[("Word文档", "*.docx"), ("所有文件", "*.*")] ) if file_path: self.input_path = file_path self.base_filename = os.path.splitext(os.path.basename(file_path))[0] self._extract_media_files() # 提取文档中的图片文件 self.source_doc = Document(file_path) # 加载原始文档 return file_path def select_output_dir(self): """选择输出目录""" root = tk.Tk() root.withdraw() dir_path = filedialog.askdirectory(title="选择输出目录") if dir_path: self.output_dir = dir_path return dir_path def _extract_media_files(self): """从Word文档中提取图片文件""" self.media_files = {} with zipfile.ZipFile(self.input_path) as z: for file in z.namelist(): if file.startswith('word/media/'): self.media_files[file] = z.read(file) def is_title(self, paragraph, level=1): """判断段落是否是标题""" # 方法1:检查样式名称 if paragraph.style.name.startswith(f'Heading {level}'): return True # 方法2:检查格式特征 if level == 1 and paragraph.runs: run = paragraph.runs[0] if run.bold and run.font.size == Pt(16): return True # 方法3:检查文本模式 text = paragraph.text.strip() if level == 1 and re.match(r'^第[一二三四五六七八九十]+章', text): return True return False def should_ignore_paragraph(self, paragraph): """判断是否应该忽略此段落""" text = paragraph.text.strip() return (not text or text in self.ignore_titles or re.match(r'^\d+$', text)) def is_useless_image(self, paragraph): """判断是否是无用图片""" return "logo" in paragraph.text.lower() def is_useless_text(self, paragraph): """判断是否是无用文本""" pattern = r'[A-Z]{1,5}(\s*[/-]\s*[A-Z]{1,5})*\s*\d+(-\d+)*' return re.fullmatch(pattern, paragraph.text.strip()) def clean_document(self, doc): """清理文档中的无用内容""" # 清理段落 for paragraph in list(doc.paragraphs): if (self.should_ignore_paragraph(paragraph) or self.is_useless_image(paragraph) or self.is_useless_text(paragraph)): self._remove_element(paragraph._element) # 清理页眉页脚 for section in doc.sections: for paragraph in section.header.paragraphs: if self.is_useless_text(paragraph): self._remove_element(paragraph._element) for paragraph in section.footer.paragraphs: if self.is_useless_text(paragraph): self._remove_element(paragraph._element) return doc def _remove_element(self, element): """删除文档元素""" if element is not None and element.getparent() is not None: element.getparent().remove(element) def process_tables(self, doc): """处理续表""" tables = doc.tables i = 0 while i < len(tables): first_cell = tables[i].cell(0, 0).text.strip().lower() if "续表" in first_cell or "continued" in first_cell: if i > 0: self._merge_tables(tables[i-1], tables[i]) self._remove_element(tables[i]._element) i -= 1 # 因为删除了一个表格,索引需要调整 i += 1 return doc def _merge_tables(self, main_table, continued_table): """合并两个表格""" start_row = 1 if continued_table.rows[0].cells[0].text.strip().lower() in ["续表", "continued"] else 0 for row in continued_table.rows[start_row:]: new_row = main_table.add_row() for i, cell in enumerate(row.cells): new_row.cells[i].text = cell.text # 复制格式 if cell._element.tcPr is not None: new_row.cells[i]._element.tcPr = parse_xml(cell._element.tcPr.xml) def split_by_chapters(self): """按章节拆分文档""" doc = self.source_doc doc = self.clean_document(doc) doc = self.process_tables(doc) chapters = [] current_chapter = None current_chapter_title = None # 获取文档主体中的所有元素 body_elements = doc.element.body.xpath('*') for element in body_elements: if element.tag.endswith('p'): # 段落 paragraph = self._get_paragraph(doc, element) if paragraph is None: continue if self.should_ignore_paragraph(paragraph): continue if self.is_title(paragraph, level=1): if current_chapter is not None: chapters.append((current_chapter_title, current_chapter)) current_chapter_title = self._format_chapter_title(paragraph.text) current_chapter = Document() # 复制文档的核心样式 self._copy_core_styles(doc, current_chapter) current_chapter.add_heading(current_chapter_title, level=1) self.current_title_path = [current_chapter_title] self.chapter_counter += 1 continue if current_chapter is not None: self._copy_paragraph(current_chapter, paragraph) elif element.tag.endswith('tbl'): # 表格 if current_chapter is not None: self._copy_table(current_chapter, element) elif element.tag.endswith('drawing'): # 图片 if current_chapter is not None: self._copy_image(current_chapter, element) if current_chapter is not None: chapters.append((current_chapter_title, current_chapter)) return chapters def _copy_core_styles(self, source_doc, target_doc): """复制核心样式到目标文档""" # 复制默认段落样式 default_style = source_doc.styles['Normal'] target_style = target_doc.styles['Normal'] target_style.font.name = default_style.font.name target_style.font.size = default_style.font.size def _get_paragraph(self, doc, element): """获取段落对象""" for p in doc.paragraphs: if p._element == element: return p return None def _format_chapter_title(self, title): """格式化章节标题""" title = title.strip() if not re.match(r'^第[一二三四五六七八九十]+章', title): match = re.search(r'(第[一二三四五六七八九十]+章\s*.+)', title) if match: title = match.group(1) return title def _copy_paragraph(self, target_doc, source_paragraph): """复制段落及其内容""" new_para = target_doc.add_paragraph(style=source_paragraph.style) # 复制段落格式 new_para.paragraph_format.alignment = source_paragraph.paragraph_format.alignment new_para.paragraph_format.left_indent = source_paragraph.paragraph_format.left_indent new_para.paragraph_format.right_indent = source_paragraph.paragraph_format.right_indent new_para.paragraph_format.first_line_indent = source_paragraph.paragraph_format.first_line_indent new_para.paragraph_format.line_spacing = source_paragraph.paragraph_format.line_spacing new_para.paragraph_format.space_before = source_paragraph.paragraph_format.space_before new_para.paragraph_format.space_after = source_paragraph.paragraph_format.space_after # 复制run和图片 for run in source_paragraph.runs: new_run = new_para.add_run(run.text) new_run.bold = run.bold new_run.italic = run.italic new_run.underline = run.underline new_run.font.size = run.font.size new_run.font.name = run.font.name # 复制图片 if run._element.xpath('.//wp:inline'): self._copy_run_image(new_run, run) def _copy_run_image(self, new_run, source_run): """复制run中的图片""" drawing = source_run._element.xpath('.//wp:inline')[0] new_run._element.append(parse_xml(drawing.xml)) def _copy_table(self, target_doc, table_element): """复制表格""" new_table = target_doc.add_table(rows=1, cols=1) new_table._element = parse_xml(table_element.xml) # 确保表格中的图片引用正确 for row in new_table.rows: for cell in row.cells: for paragraph in cell.paragraphs: for run in paragraph.runs: if run._element.xpath('.//wp:inline'): self._copy_run_image(run, run) def _copy_image(self, target_doc, image_element): """复制独立图片""" para = target_doc.add_paragraph() run = para.add_run() run._element.append(parse_xml(image_element.xml)) def save_chapters(self, chapters): """保存章节并处理图片引用""" if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) saved_files = [] for idx, (title, chapter_doc) in enumerate(chapters): # 生成安全的文件名 safe_title = re.sub(r'[\\/*?:"<>|]', "_", title) # 使用基础文件名+章节标题作为文件名 filename = f"{self.base_filename}-{safe_title}.docx" filepath = os.path.join(self.output_dir, filename) # 临时保存以处理图片 temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.docx') chapter_doc.save(temp_file.name) temp_file.close() # 处理图片引用 self._repack_docx_with_images(temp_file.name, filepath) os.unlink(temp_file.name) saved_files.append(filepath) return saved_files def _repack_docx_with_images(self, src_path, dest_path): """重新打包docx文件包含图片""" with zipfile.ZipFile(src_path, 'r') as zin: with zipfile.ZipFile(dest_path, 'w') as zout: # 复制所有文件 for item in zin.infolist(): if not item.filename.startswith('word/media/'): # 不复制原media文件 zout.writestr(item, zin.read(item.filename)) # 添加图片文件 for rel_path, data in self.media_files.items(): zout.writestr(rel_path, data) def _extract_chapter_number(self, title): """从标题中提取章节编号""" match = re.search(r'第([一二三四五六七八九十]+)章', title) if match: chinese_num = match.group(1) num_map = {'一':'1','二':'2','三':'3','四':'4','五':'5', '六':'6','七':'7','八':'8','九':'9','十':'10'} return num_map.get(chinese_num, None) return None def process_document(self): """处理文档主流程""" if not self.input_path or not os.path.exists(self.input_path): raise FileNotFoundError("输入文件路径无效或文件不存在") if not self.output_dir: raise ValueError("输出目录未指定") try: chapters = self.split_by_chapters() saved_files = self.save_chapters(chapters) return saved_files except Exception as e: raise Exception(f"处理文档时出错: {str(e)}") def main(): """主界面""" try: processor = WordProcessor() root = tk.Tk() root.title("Word文档处理工具 v3.2") root.geometry("650x450") # 界面布局 tk.Label(root, text="Word文档高级处理工具", font=("Arial", 16)).pack(pady=10) # 输入文件选择 input_frame = tk.Frame(root) input_frame.pack(pady=5, fill=tk.X, padx=20) tk.Label(input_frame, text="输入文件:").pack(side=tk.LEFT) input_entry = tk.Entry(input_frame, width=45) input_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X) tk.Button(input_frame, text="浏览...", command=lambda: input_entry.insert(0, processor.select_input_file())).pack(side=tk.LEFT) # 输出目录选择 output_frame = tk.Frame(root) output_frame.pack(pady=5, fill=tk.X, padx=20) tk.Label(output_frame, text="输出目录:").pack(side=tk.LEFT) output_entry = tk.Entry(output_frame, width=45) output_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X) tk.Button(output_frame, text="浏览...", command=lambda: output_entry.insert(0, processor.select_output_dir())).pack(side=tk.LEFT) # 处理按钮 def on_process(): processor.input_path = input_entry.get() processor.output_dir = output_entry.get() if not processor.input_path: messagebox.showerror("错误", "请先选择输入文件") return if not processor.output_dir: messagebox.showerror("错误", "请先选择输出目录") return try: saved_files = processor.process_document() messagebox.showinfo("成功", f"处理完成! 共生成 {len(saved_files)} 个子文档。\n" f"输出目录: {processor.output_dir}\n" f"第一个文件: {os.path.basename(saved_files[0])}") # 打开输出目录 if os.name == 'nt': # Windows os.startfile(processor.output_dir) elif os.name == 'posix': # macOS, Linux os.system(f'open "{processor.output_dir}"') except Exception as e: messagebox.showerror("错误", f"处理失败: {str(e)}") process_btn = tk.Button(root, text="开始处理", command=on_process, height=2, width=20, bg="#4CAF50", fg="white") process_btn.pack(pady=20) # 说明文本 info_frame = tk.Frame(root, borderwidth=1, relief="solid", padx=10, pady=10) info_frame.pack(pady=10, padx=20, fill=tk.BOTH, expand=True) tk.Label(info_frame, text="功能说明:", font=("Arial", 10, "bold")).pack(anchor="w") tk.Label(info_frame, text="1. 按章节拆分文档,保留原格式\n" "2. 完整保留所有表格和图片\n" "3. 自动处理续表合并\n" "4. 清理无用内容(logo、标准号等)\n" "5. 生成文件名格式: 原文件名-章节标题", justify=tk.LEFT, anchor="w").pack(fill=tk.X) tk.Label(info_frame, text="输出示例:\n" "高速公路清障施救标准化手册0901终-第一章 总则.docx\n" "高速公路清障施救标准化手册0901终-第二章 清障施救标准.docx", justify=tk.LEFT, anchor="w", fg="blue").pack(fill=tk.X, pady=(5,0)) root.mainloop() except Exception as e: messagebox.showerror("系统错误", f"程序发生错误: {str(e)}") if __name__ == "__main__": main() 我在执行上面代码的时候,被拆分的文档中所有的图片和表格都没有了,是什原因导致的我应该怎么修改
最新发布
07-16
import json from pyecharts import options as opts from pyecharts.charts import Pie, Bar, Funnel, Page, PictorialBar, WordCloud,Line from pyecharts.globals import ThemeType, SymbolType from pyspark import SparkConf, SparkContext import os # 设置 Python 环境 os.environ["PYSPARK_PYTHON"] = r"C:\Users\h\AppData\Local\Programs\Python\Python38\python.exe" # 配置 Spark conf = SparkConf().setMaster("local[*]").setAppName("GameLevelDistribution") sc = SparkContext(conf=conf) # 导入 JSON 数据 with open("game_data.json", encoding="utf-8") as f: data = json.load(f) # 将数据转换为 RDD rdd = sc.parallelize(data) # 提取 level 数据 level_rdd = rdd.map(lambda x: x.get('level', '未知等级')) # 统计每个 level 的出现次数 level_counts = level_rdd.countByValue() # 将统计结果转换为列表,格式为 [("等级1", 次数1), ("等级2", 次数2), ...] level_data = [(level, count) for level, count in level_counts.items()] # 创建饼图 def drawPie(): # 按等级从小到大排序 sorted_level_data = sorted(level_data, key=lambda x: int(x[0].replace('级', ''))) c = ( Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) .add("", sorted_level_data, center=["50%", "63%"]) .set_global_opts( title_opts=opts.TitleOpts( title="游戏等级分布", title_textstyle_opts=opts.TextStyleOpts(color="white") ), legend_opts=opts.LegendOpts( pos_left="30%", textstyle_opts=opts.TextStyleOpts(color="white"), ), toolbox_opts=opts.ToolboxOpts(is_show=False), # 隐藏工具栏 datazoom_opts=None # 禁用数据缩放 ) .set_series_opts( label_opts=opts.LabelOpts(formatter="{b}: {c}", color="white"), itemstyle_opts=opts.ItemStyleOpts(border_width=0), init_opts=opts.InitOpts(renderer='svg') ) ) return c # 统计游戏类型分布 word_counts = ( rdd.flatMap(lambda x: [word.strip() for word in x["type"].split("/") if word.strip()]) .map(lambda word: (word, 1)) .reduceByKey(lambda x, y: x + y) .collect() ) # 将统计结果转换为漏斗图需要的格式 funnel_data = [(word, count) for word, count in word_counts] # 创建漏斗图 def drawFunnel(): l = ( Funnel(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) .add( series_name="游戏类型分布", data_pair=funnel_data, gap=2, tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b} : {c}"), label_opts=opts.LabelOpts( is_show=True, position="inside", color="white" ), itemstyle_opts=opts.ItemStyleOpts( border_color="#fff", border_width=0 ), ) .set_global_opts( title_opts=opts.TitleOpts( title="游戏类型分布漏斗图", title_textstyle_opts=opts.TextStyleOpts(color="white") ), legend_opts=opts.LegendOpts( pos_top="bottom", pos_left="center", textstyle_opts=opts.TextStyleOpts(color="white") ), toolbox_opts=opts.ToolboxOpts(is_show=False), # 隐藏工具栏 datazoom_opts=None # 禁用数据缩放 ) ) return l # 统计游戏类型分布及平均评分 def split_types(game): types = game["type"].split(" / ") return [(t.strip(), 1) for t in types] type_counts = rdd.flatMap(split_types).reduceByKey(lambda a, b: a + b).collectAsMap() def split_types_with_score(game): types = game["type"].split(" / ") score = float(game["score"]) return [(t.strip(), score) for t in types] type_scores = ( rdd.flatMap(split_types_with_score) .groupByKey() .mapValues(lambda scores: round(sum(scores) / len(scores), 2)) .collectAsMap() ) # 准备数据 types = list(type_counts.keys()) counts = [type_counts[t] for t in types] scores = [f"{score:.2f}" for score in [type_scores[t] for t in types]] # 创建柱状图 def drawLine(): line = ( Line(init_opts=opts.InitOpts(theme="light")) .add_xaxis(xaxis_data=types) .add_yaxis( series_name="游戏数量", y_axis=counts, markpoint_opts=opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ] ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均值")] ), ) .add_yaxis( series_name="平均评分", y_axis=scores, markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_="max", name="最高评分")] ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均评分")] ), ) .set_global_opts( title_opts=opts.TitleOpts( title="游戏类型分布", subtitle="纯属虚构", title_textstyle_opts=opts.TextStyleOpts(color="white") ), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), toolbox_opts=opts.ToolboxOpts(is_show=True), xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False), yaxis_opts=opts.AxisOpts( name="数量/评分", axislabel_opts=opts.LabelOpts( formatter="{value}", color="white" ) ), legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="white")), datazoom_opts=None ) ) return line # 统计每一年的游戏数量 year_counts = rdd.map(lambda x: (x['year'], 1)).reduceByKey(lambda a, b: a + b).collect() # 将结果转换为字典,方便后续处理 year_counts_dict = dict(year_counts) # 分离“公元前”和普通年份 bc_years = {year: count for year, count in year_counts_dict.items() if '公元前' in year} ad_years = {year: count for year, count in year_counts_dict.items() if '公元前' not in year} # 对“公元前”年份进行排序(按绝对值降序) sorted_bc_years = sorted(bc_years.keys(), key=lambda x: int(x.replace('公元前', '')), reverse=True) # 对普通年份进行排序(按升序) sorted_ad_years = sorted(ad_years.keys(), key=lambda x: int(x)) # 合并排序后的年份 sorted_years = sorted_bc_years + sorted_ad_years # 准备柱状图数据 x_axis = sorted_years # 按排序后的年份 y_axis = [year_counts_dict[year] for year in sorted_years] # 对应的游戏数量 # 创建每年游戏数量统计的柱状图 def drawYearBar(): bar = ( Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) .add_xaxis(x_axis) .add_yaxis("游戏数量", y_axis) .set_global_opts( title_opts=opts.TitleOpts( title="每年游戏数量统计", title_textstyle_opts=opts.TextStyleOpts(color="white") ), datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts( rotate=-15, color="white" ) ), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(color="white") ), legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="white")), toolbox_opts=opts.ToolboxOpts(is_show=False), # 隐藏工具栏 ) ) return bar # 1. 桌游类型词云图 wordCount = ( rdd.flatMap(lambda x: [word.strip() for word in x["type"].split("/") if word.strip()]) .map(lambda word: (word, 1)) .reduceByKey(lambda x, y: x + y) ) def draw_wordcloud() -> WordCloud: wc = ( WordCloud() .add(series_name="", data_pair=wordCount.collect(), word_size_range=[10, 60]) .set_global_opts( title_opts=opts.TitleOpts( title="桌游类型统计", title_textstyle_opts=opts.TextStyleOpts(font_size=20, color="white"), pos_left="center" ), tooltip_opts=opts.TooltipOpts(is_show=True), toolbox_opts=opts.ToolboxOpts(is_show=False), # 隐藏工具栏 datazoom_opts=None ) ) return wc # 2. 桌游时长象形柱状图(第11-20名) selected_data = data[10:20] titles = [game["title"] for game in selected_data] times = [int(game["time_per_person"].replace("分/人", "")) for game in selected_data] def draw_pictorialbar() -> PictorialBar: pb = ( PictorialBar() .add_xaxis(titles) .add_yaxis( "人均游戏时长(分钟)", times, label_opts=opts.LabelOpts(is_show=True, color="white"), symbol_size=22, symbol_repeat="fixed", symbol_offset=[0, 0], is_symbol_clip=True, symbol=SymbolType.ROUND_RECT, color="#37A2DA" ) .reversal_axis() .set_global_opts( title_opts=opts.TitleOpts( title="11-20名桌游人均耗时象形图", title_textstyle_opts=opts.TextStyleOpts(color="white") ), legend_opts=opts.LegendOpts(pos_top="5%"), yaxis_opts=opts.AxisOpts( axistick_opts=opts.AxisTickOpts(is_show=False), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(opacity=0) ), axislabel_opts=opts.LabelOpts(color="white"), ), xaxis_opts=opts.AxisOpts( name="时长(分钟)", axislabel_opts=opts.LabelOpts(font_size=12, color="white"), splitline_opts=opts.SplitLineOpts(is_show=True), ), tooltip_opts=opts.TooltipOpts(is_show=True), toolbox_opts=opts.ToolboxOpts(is_show=False), # 隐藏工具栏 datazoom_opts=None ) ) return pb# 创建Page对象 page = Page(layout=Page.DraggablePageLayout) # 添加图表 page.add( drawPie(), drawFunnel(), drawLine(), drawYearBar(), draw_wordcloud(), draw_pictorialbar() ) # 将自定义HTML内容嵌入到最终的HTML文件中 html_content += page.render_embed() html_content += "</body></html>" # 将完整的HTML内容写入文件 with open("jishi2.html", "w", encoding="utf-8") as f: f.write(html_content) # 额外的逻辑,用于调整图表的排版 from bs4 import BeautifulSoup # 打开并读取 HTML 文件 with open("jishi2.html", "r+", encoding='utf-8') as html: html_bf = BeautifulSoup(html, 'lxml') # 选择所有具有类名 'chart-container' 的 div 元素 divs = html_bf.select('.chart-container') # 检查是否有足够的 div 元素 if len(divs) < 6: print("HTML 文件中 .chart-container 元素不足 6 个") else: # 设置每个 div 的样式 divs[0]["style"] = "width:20%;height:30%;position:absolute;bottom:0;left:5%;" # 左下方 divs[1]["style"] = "width:25%;height:26%;position:absolute;top:20%;right:0;" # 右上方 divs[2]["style"] = "width:40%;height:30%;position:absolute;bottom:0;left:30%;" # 中间的下面 divs[3]["style"] = "width:25%;height:25%;position:absolute;top:50%;right:0;" # 右边的中间 divs[4]["style"] = "width:20%;height:10%;position:absolute;bottom:5%;right:3%;" # 右下角 divs[5]["style"] = "width:35%;height:40%;position:absolute;top:20%;left:1%;" # 左上方 # 修改 body 的样式 body = html_bf.find("body") body["style"] = "background-image: url('img/backGround.png'); background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-color: #464646;" # 将修改后的内容写回文件 html_new = str(html_bf) html.seek(0, 0) html.truncate() html.write(html_new) html.close()为什么这段代码运行出来,图表在页面中,鼠标可以改变图表的位置,我应该怎么解决这一问题
06-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值