既にコーディングしたものを一括変換するために

行単位の置換処理と文字列単位の置換処理プログラムを作って。

 

【Copilotの答えの始め】

 

replace_lines.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import re

def replace_lines_in_file(file_path, replace_rules):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # ファイル全体を一つの文字列として読み込む
    content = ''.join(lines)
    for search_patterns, replace_lines in replace_rules:
        for search_pattern in search_patterns:
            pattern = re.compile(search_pattern, re.DOTALL)
            if not replace_lines:
                content = pattern.sub('', content)
            else:
                content = pattern.sub('\n'.join(replace_lines), content)
    
    # 空行を調整:連続する空行を1行に制限する
    new_lines = []
    for line in content.splitlines():
        if line.strip() or (new_lines and new_lines[-1].strip()):
            new_lines.append(line)
    
    # 各行に改行を追加
    new_lines = [line + '\n' for line in new_lines]

    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(new_lines)

def process_files_for_line_replacement(directory, replace_rules):
    for root, _, files in os.walk(directory):
        for file_name in files:
            if file_name.endswith('.py'):
                file_path = os.path.join(root, file_name)
                try:
                    replace_lines_in_file(file_path, replace_rules)
                except Exception as e:
                    print(f"Error processing file {file_path}: {e}")


# 例:行置換ルールのリスト
replace_rules = [
    (['(?s)import db'], ['from sqlalchemy.orm import sessionmaker', 'import db2']),
    (['(?s)conn_pool=db\\.get_connection_pool\\(\\)'], ['DbSession = sessionmaker(bind=db2.engine)', 'db_session = DbSession()']),
    (['(?s)conn=conn_pool\\.get_connection\\(\\)', r'(?s)cursor = conn\\.cursor\\(buffered=True\\)'], []),
    # 他の置換ルールを追加できます
]

process_files_for_line_replacement('開始するディレクトリー', replace_rules)
replace_words.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import os
import re

def replace_words_in_file(file_path, replace_rules):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    new_lines = []
    for line in lines:
        if line.strip().startswith('#'):
            new_lines.append(line)
            continue
        new_line = line
        for search_word, replace_word in replace_rules:
            new_line = re.sub(search_word, replace_word, new_line)
        new_lines.append(new_line)

    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(new_lines)

def process_files_for_word_replacement(directory, replace_rules):
    for root, _, files in os.walk(directory):
        for file_name in files:
            if file_name.endswith('.py'):
                file_path = os.path.join(root, file_name)
                try:
                    replace_words_in_file(file_path, replace_rules)
                except Exception as e:
                    print(f"Error processing file {file_path}: {e}")

# 例:単語置換ルールのリスト
replace_rules = [
    (r'cursor\.execute', 'result=db_session.execute'),
    (r'cursor.fetchall', 'result.fetchall'),
    (r'cursor\.fetchone', 'result.fetchone'),
    (r'conn\.commit', 'db_session.commit'),
    (r'conn\.rollback', 'db_session.rollback'),
    (r'conn\.Error as err', 'Exception as e'),
    (r'conn\.close\(\)', ''),
    (r'cursor\.close\(\)', 'db_session.close()'),
    (r'cursor', 'db_session'),
    # 他の置換ルールを追加できます
]
process_files_for_word_replacement('開始するディレクトリー', replace_rules)

【Copilotの答えの終わり】

 

 

 

 

雁一羽悠然と落日へゆく