【Python】Python で DOT言語による Animation tool 作成

■ はじめに

超個人的なツール。

https://dk521123.hatenablog.com/entry/2023/06/18/102448

と組み合わせればアニメーションで動くものになるので。

【1】サンプル

フォルダ構成

+ dot_viewer_creator.py
+ delete
  + 01.txt
  + 02.txt
  + 03.txt
+ add
  + 01.txt
  + 03.txt
+ input
  + input.dot

delete

01.txt

table3
table4

02.txt

table9

03.txt

table10

add

01.txt

    A -> B -> C;

02.txt

    B -> D;

input

input.dot

digraph {
    graph [rankdir=LR]
    node [fontname="MS Gothic"]
    table1
    table2
    table3
    table4
    table1 -> table2
    table2 -> table3
    table2 -> table4
}

import os
import shutil

input_file_path = 'hello.dot'

output_file_format = 'hello_out_{:0=2}.dot'
out_path = 'out1'
delete_path = './delete'
add_path = './add'
replaced_sign = '    # ADD HERE'

def can_find(lines, delete_list):
  for delete_table in delete_list:
    if (delete_table in lines):
      return True
  return False

if os.path.isdir(out_path):
  # あったら削除
  shutil.rmtree(out_path)
# 再作成
os.makedirs(out_path)

for i, file_name in enumerate(os.listdir(delete_path)):
  no = i + 1
  print(f'************* no = {no} *************')

  # Delete
  delete_file_path = os.path.join(delete_path, file_name)
  with open(delete_file_path, 'r', encoding='utf-8') as file:
    delete_list = file.read().splitlines()

  output_file = output_file_format.format(no)
  output_file_path = os.path.join(out_path, output_file)
  print(f'input_file_path={input_file_path}, output_file_path={output_file_path}')
  with open(input_file_path, 'r', encoding='utf-8') as file:
    line_number = 1
    lines = file.readline()
    while lines:
      print(f'{line_number} - {lines}')
      if (can_find(lines, delete_list)):
        print(f"Found, Skip!!! {lines}")
      else:
        # 追記モード
        with open(output_file_path, mode='a') as out_file:
          out_file.write(lines)
      line_number = line_number + 1
      lines = file.readline()

  input_file_path = output_file_path

  # ADD
  add_file_path = os.path.join(add_path, file_name)
  print(f'add_file_path = {add_file_path}')
  if(not os.path.isfile(add_file_path)):
    print(f'Skip! {add_file_path}')
    continue

  print(f'add_file_path = {add_file_path}')
  with open(add_file_path, 'r', encoding='utf-8') as file:
    add_dot = file.read()
    print(f'add_dot = {add_dot}')
  with open(input_file_path, 'r', encoding='utf-8') as in_file:
    input_content = in_file.read()
  
  print(f'input_content = {input_content}')
  output_content = input_content.replace(
    replaced_sign, replaced_sign + '\n' + add_dot)
  print(f'output_content = {output_content}')
  with open(input_file_path, 'w', encoding='utf-8') as out_file:
    out_file.write(output_content)

print('DONE')

関連記事

Python + DOT言語で図作成するには
https://dk521123.hatenablog.com/entry/2023/06/14/174104
Python ~ 基本編 / パス情報抽出 ~
https://dk521123.hatenablog.com/entry/2022/02/23/000000
Python ~ 基本編 / フォルダ・ファイル操作 ~
https://dk521123.hatenablog.com/entry/2019/09/02/000000