我的输入数据是:
昂
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
我想要的输出应该是:
ANG
0.0
0.0
0.0
0.0
0.0
0.0
0.0
100
0.3
我使用类和函数编写了代码。 这是我的代码。
class Calculate:
def angCal(self,dir,mag,string):
cnt=0
if cnt<=6:
f4.write(string)
cnt+=1
elif cnt==7:
string=str(dir)+"\n"
f4.write(string)
cnt+=1
elif cnt==8:
string=str(mag)+"\n"
f4.write(string)
cnt+=1
if cnt==9:
f4.write(string)
cnt+=1
obj=Calculate()
f4=open("Out.txt",'w')
f1=open("Input.txt",'r')
for line in f1.readlines():
string=line
if re.match(r'ANG',string):
dir=100
mag=0.3
obj.angCal(dir,mag,string)
代码无法正常工作。请帮助
答案 0 :(得分:0)
您应该正确缩进代码,实例化Calculate
对象,使angCal
接受self
,因为它是实例方法,请使用循环遍历输入字符串的行拆分后,并解决您的if
条件:
import re
class Calculate:
def __init__(self, file):
self.file = file
def angCal(self, dir, mag, string):
cnt = 0
for line in string.splitlines():
if cnt == 8:
self.file.write(dir)
elif cnt == 9:
self.file.write(mag)
else:
self.file.write(line)
self.file.write('\n')
cnt += 1
with open('input.txt') as f:
string = f.read()
with open('output.txt', 'w') as f4:
obj = Calculate(f4)
if re.match(r'ANG', string):
dir = 100
mag = 0.3
obj.angCal(dir, mag, string)