2024-05-20
今まで、大量のサーベイ出力データから必要個所のみ摘出し、エクセルで処理するという作業を、結構な手作業(grepなど)により行ってきたが、ChatGPTの助けを借りて作成した。(エラーの多い適当なプログラムをコピペしてアップすると、修正して正しいプロゴラムとして回答してくれた。)これで作業効率は10倍程度アップするし、データ抽出ミスが少なると予想される。
そのPythonプログラム例は下記の通り。
条件としては、あるフォルダーに多数(P01〜P99まで)のサーベイ計算出力ファイルがあり、
各出力ファイルのなかの5つの検索キーワードを指定し、その2行、4行下の行内のある部分を抽出し、平均化したり、抽出したデータをエクセルで処理しやすいよう行データとしてリスト化するというものである。
Pythonはテキストと数値の形式変換を繰り返すのでやや冗長になってはいるが、ChatGPTのおかげで元のプログラムの半分以下の行数になった。
import os
def extract_value(line, start, end):
"""指定された範囲から数値を抽出して返す"""
try:
return float(line[start:end])
except ValueError:
return None
f2out = open("RRATECS.txt", "w")
num = 1
print("num")
while num in range(10):
directory =os. getcwd()
partial_name = 'P0' + str(num)
keyword1 = " & ID(1)"
keyword2 = " & ID(2)"
keyword3 = " & ID(3)"
keyword4 = " <TA1> "
keyword5 = " <TA2> "
for file_name in os.listdir(directory):
if partial_name in file_name:
with open(os.path.join(directory, file_name), 'r') as fileo:
lines = fileo.readlines()
if lines:
nd1, nd2, nd3, rr1, cs1= None, None, None, None, None
for i, line in enumerate(lines):
if keyword1 in line and i + 2 < len(lines):
nd1 = extract_value(lines[i + 2], 24, 37)
if keyword2 in line and i + 2 < len(lines):
nd2 = extract_value(lines[i + 2], 24, 37)
if keyword3 in line and i + 2 < len(lines):
nd3 = extract_value(lines[i + 2], 24, 37)
if keyword4 in line and i + 4 < len(lines):
rr1 =float(extract_value(lines[i + 4], 18, 30))
if keyword5 in line and i + 4 < len(lines):
cs1 =float(extract_value(lines[i + 4], 18, 30))
if nd1 is not None and nd2 is not None and nd3 is not None:
avnd = float((nd1 + nd2 + nd3) / 3)
e_type_avnd=format(avnd, ".4E")
e_type_rr1=format(rr1, ".5E")
e_type_cs1=format(cs1, ".5E")
print(num,e_type_rr1,e_type_cs1,e_type_avnd)
numint=str(num)
rr1txt=str(e_type_rr1)
cs1txt=str(e_type_cs1)
avnntxt=str(e_type_avnd)
txtwrite=numint+" "+rr1txt+" "+cs1txt+" "+avnntxt+"\n"
f2out.write(txtwrite)
num += 1
while num in range(10, 100):
directory = os. getcwd()
partial_name = 'P' + str(num)
keyword1 = " & ID(1)"
keyword2 = " & ID(2)"
keyword3 = " & ID(3)"
keyword4 = " <TA1> "
keyword5 = " <TA2> "
# f2out = open("RRATECS.txt", "a")
for file_name in os.listdir(directory):
if partial_name in file_name:
with open(os.path.join(directory, file_name), 'r') as fileo:
lines = fileo.readlines()
if lines:
nd1, nd2, nd3, rr1, cs1= None, None, None, None, None
for i, line in enumerate(lines):
セ記事を書く
セコメントをする