【Python】tkinterでテキストの中の文字を置換するツール作ってみた

プログラミング
広告
広告

皆さんこんにちは!

特定のテキストをWordやExcelで開いて、手動で置換作業を行うのは面倒ですよね。
そこで今回は、Pythonライブラリ「tkinter」を用いて、テキスト置換を簡単に実行できるツールを作成しました。

コードを実際に動かしてみるとPythonの勉強になるので活用していただければと思います。

広告
広告

ツールの概要

このツールは、以下の機能を提供します。

  • シンプルな操作で、誰でも簡単に利用可能
  • テキスト内の文字を効率的に置換
  • 置換前後の用語を自由に設定可能
  • 置換結果をリアルタイムで確認
  • ボタン操作でテキストをクリア可能

コード一覧

import tkinter as tk


def replace_text():
    original_text = text_input.get("1.0", "end-1c")
    original_word = original_word_input.get()
    replacement_word = replacement_word_input.get()

    if not original_text.strip():  # 置換対象のテキストが空の場合、エラーメッセージを表示
        text_output.delete("1.0", "end")
        text_output.insert("1.0", "Error: 置換対象のテキストが空です。")
    elif not original_word:  # 置換前の用語が入力されていない場合、エラーメッセージを表示
        text_output.delete("1.0", "end")
        text_output.insert("1.0", "Error: 置換前の用語を入力してください。")
    else:
        replaced_text = original_text.replace(original_word, replacement_word)
        text_output.delete("1.0", "end")
        text_output.insert("1.0", replaced_text)


def clear_text():
    text_input.delete("1.0", "end")
    text_output.delete("1.0", "end")
    original_word_input.delete(0, "end")
    replacement_word_input.delete(0, "end")


# GUIの設定
root = tk.Tk()
root.title("テキスト置換ツール")
root.geometry("600x500")  # ウィンドウの初期サイズを設定

# 対象のテキスト
text_label = tk.Label(root, text="置換対象のテキスト")
text_label.pack()
text_input = tk.Text(root, height=10, width=50)
text_input.pack()

# 置換前の用語
original_word_label = tk.Label(root, text="置換前の用語")
original_word_label.pack()
original_word_input = tk.Entry(root)
original_word_input.pack()

# 置換後の用語
replacement_word_label = tk.Label(root, text="置換後の用語")
replacement_word_label.pack()
replacement_word_input = tk.Entry(root)
replacement_word_input.pack()

# 置換ボタン
replace_button = tk.Button(root, text="テキストを置換", command=replace_text)
replace_button.pack()

# 置換結果の表示
text_output_label = tk.Label(root, text="置換後のテキスト")
text_output_label.pack()
text_output = tk.Text(root, height=10, width=50)
text_output.pack()

# テキストクリアボタン
clear_button = tk.Button(root, text="テキストをクリア", command=clear_text)
clear_button.pack(pady=5)  # ボタンを少し離す

root.mainloop()

※コードの利用は注意してご使用ください。

使用例

このコードを実行すると以下の画像のような初期画面が表示されます。

使用例としては以下の通りです。
「置換対象のテキスト中」にある用語を変換するシンプルなツールになっています。

「置換前の用語」に半角スペースを入れると、
英文の間にある空白を「-」に置換するといったちょっと特殊な使い方もできます。

最後に

テキスト置換方法自体は他にもいくらでもありますのでpythonのプログラミング勉強の参考になればと思います。初心者用の学習としても利用できるはずです。

今回作成したコードとexeは下記リンク先に保存しています。
ファイル名は「word_conversion.py」です。
また、exeファイルも作成しているのでダウンロードしたい方は下記リンクから右にある「Releases」を選択し、表示された該当のexeファイルをダウンロードしてください。

GitHub - technyanko/python_tools
Contribute to technyanko/python_tools development by creating an account on GitHub.
人気ブログランキング

クリックするとブログランキングサイトに移動します。

にほんブログ村 IT技術ブログへ
インターネット・コンピュータランキング
広告
広告
プログラミング
広告
technyankoをフォローする
広告
プロフィール
technyanko

元情シス・SEです。
当ブログではPCに関して困ったことや役立つ情報を発信していきます。
たまにバッチスクリプトやPythonに関する記事も投稿します。

technyankoをフォローする
広告
タイトルとURLをコピーしました