田中太郎
置換したいキーワードをエクセルで管理して,
文字列をいっきに置換するよ!
サンプルコード
文字列を置換
文字列をエクセルファイルにあるキーワードを基に置換します.
入力
・文字列
'" < > ^ ~ - * /'
・キーワードを記入したエクセルファイル(exchange.xlsx)
出力
・置換後の文字列
" < > ˆ ˜ − ∗ ⁄
コード
""" A -> B by excel file."""
import pandas as pd
def create_line_list(excel_file):
df = pd.read_excel(excel_file, header=None)
df = df.fillna("NA")
df = df.T
data_dict = df.to_dict(orient="list")
lines = list(data_dict.values())
return lines
def exchange_line(excel_file, strA):
excel_data = create_line_list(excel_file)
for word in excel_data:
if word[0] in strA:
strA = strA.replace(
word[0],
word[1],
)
return strA
strA = '" < > ^ ~ - * /'
print(exchange_line("exchange.xlsx", strA))
解説
def create_line_list(input_excel)
では,エクセルファイルを読み込み,以下のリストを作成します.
[[(行1,列1),(行1,列2),(行1,列3)],[(行2,列1),(行2,列2),(行2,列3)],[…],…]
def exchange_line(“exchange.xlsx”, strA):
では,”exchange.xlsx”に入っているキーワードを基にstrAの文字列を置換します.
コメント