gpt4 book ai didi

python - 使用继承 python34 创建交互式命令循环

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:27 25 4
gpt4 key购买 nike

我正在尝试了解如何以可以使用继承方法的方式构建脚本。我对 python 还很陌生。我的问题是在一个类中使用另一个类定义的变量。我最近刚刚了解了 super 函数,但我认为我没有正确使用它,因为它不断打印并重新计算它从中提取的所有内容。

假设我在一个文本文件中收到了一堆消息,这些消息以逗号分隔,为我提供了不同的信息。我希望能够获取该文本文件并且...

  1. 能够阅读以逗号分隔的内容(完成)
  2. 告诉我每种类型的消息有多少(已完成)
  3. 然后创建一个名为 messages 的类,其中包含每种类型消息的定义及其在这些实例中创建的各自的计算和变量(完成)
  4. 创建类来在客户端和 xls 中打印和写入这些计算和变量(由于我的问题部分完成)
  5. 创建类以将 xls 转换为 csv 和 kml(已完成)
<小时/>

这是我正在使用的玩具结构

<小时/>
import bunch of stuff


data = [] #empty because we will store data into it


#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""

for row in csv.reader(open(filename)):
data.append(row)
return data

with open(path_in + data_file) as csvfile:
read_it = list(csv.reader(csvfile, delimiter=','))


#Counts the number of times a GPS command is observed
def list_msg_type_countdata):
"""Counts the number of times a GPS command is observed.

Returns a dictionary object."""

msg_count = dict()
for row in data:
try:
msg_count[row[0]] += 1
except KeyError:
msg_count[row[0]] = 1

return msg_count

print(list_msg_type_count(read_it))
print ("- - - - - - - - - - - - -")


class CreateWorkbook:
def openworkbook(self, data):
global output_filename
output_filename = input('output filename:')
global workbook
workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
self.worksheet = workbook.add_worksheet()
#formatting definitions
global bold
bold = workbook.add_format({'bold': True})
global date_format
date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"})
global time_format
time_format = workbook.add_format({'num_format': "hh:mm:ss"})

def closeworkbook_gprmc(self, data):
print('closeworkbook')
#pull data from process_msg1
(i1, i2, i3) = messagetype.process_msg1(data)
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
workbook.close()
f.close()
print('XLSX file named ' + output_filename + '_' + command_type +' was created')

def closeworkbook_msg2(self, data):
#pull data from process_msg2
(i1, i2, i3, i4) = messagetype.process_msg2(data)
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.write('C1', 'item4',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.worksheet.write_column(r,3, i4)
workbook.close()
f.close()
print('XLSX file named ' + output_filename + '_' + command_type + ' was created')


class ConvertFile
def convert2csv(self, data):
# set path to folder containing xlsx files
os.chdir(path_out)

# find the file with extension .xlsx
xlsx = glob.glob(output_filename + '_' + command_type + '.xlsx')

# create output filenames with extension .csv
csvs = [x.replace('.xlsx','.csv') for x in xlsx]

# zip into a list of tuples
in_out = zip(xlsx,csvs)

# loop through each file, calling the in2csv utility from subprocess
for xl,csv in in_out:
out = open(csv,'w')
command = 'c:/python34/scripts/in2csv %s\\%s' % (path_out,xl)
proc = subprocess.Popen(command,stdout=out)
proc.wait()
out.close()
print('CSV file named ' + output_filename + '_' + command_type + ' was created')

def convert2kml(self, data):
#Input the file name.
h = open(path_out + output_filename + '_' + command_type + '.csv')
with h as csvfile2:
data2 = csv.reader(csvfile2,delimiter=',')
next(data2)

#Open the file to be written.
g = open(output_filename + '_' + command_type +'.kml','w')
g.write("<?xml version='1.0' encoding='UTF-8'?>\n")
g.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
g.write("<Document>\n")
g.write(" <name>" + output_filename + '_' + command_type + '.kml' +"</name>\n")
for row in data2:
g.write(" <Placemark>\n")
g.write("<TimeStamp><when>" + str(row[0]) + "</when></TimeStamp>\n")
g.write(" <Point>\n")
g.write(" <coordinates>" + str(row[2]) + "," + str(row[1]) + "</coordinates>\n")
g.write(" </Point>\n")
g.write(" </Placemark>\n")


g.write("</Document>\n")
g.write("</kml>\n")
g.close()
h.close()
print('and ' + output_filename + '_' + command_type +'.kml was created,too!')


class MessageType:
def process_msg1(self,data)
item1 = []
item2 = []
item3 = []

print('printing stuff')

for r in data:
if row[0] == 'msg type1'
item1.append('calculations')
item2.append('calculations')
item3.append('calculations')
print('calculations done')
return(array(item1),array(item2),array(item3))

def process_msg2(self,data)
item1 = []
item2 = []
item3 = []
item4 = []

print('printing stuff')

for r in data:
if row[0] == 'msg type1'
item1.append('calculations')
item2.append('calculations')
item3.append('calculations')
item4.append('calculations')
print('calculations done')
return(array(item1),array(item2),array(item3),array(item4))

class PrintMSG(MessageType):
def process_msg1(self, data):
(i1, i2, i3) = super(PrintMSG, self).process_msg1(data)
print('printing plus plotting using variables from class Message')

def process_msg2(self, data):
(i1, i2, i3,i4) = super(PrintMSG, self).process_msg2(data)
print('printing plus plotting using variables from class Message')


#processing piece
keep_asking = True
while keep_asking:
command_type = input("What message type do you want to look at?")
if command_type == 'msg type1':
createworkbook = CreateWorkbook()
createworkbook.openworkbook(data)
msg = MessageType()
print_msg = PrintMSG()
print_msg.process_msg1(data)
createworkbook.closeworkbook_msg1(data)
convert2csv(data)
convert2kml(data)
elif command_type == 'msg type2':
createworkbook = CreateWorkbook()
createworkbook.openworkbook(data)
msg = MessageType()
print_msg = PrintMSG()
print_msg.process_msg2(data)
createworkbook.closeworkbook_msg2(data)
convert2csv(data)
convert2kml(data)
else:
print("Invalid type:", command_type)

wannalook = input('Want to look at another message or no?')
if not wannalook.startswith('y'):
keep_asking = False

最佳答案

类定义

代码有点大,有很多东西不起作用或可以改进。作为初学者,请学习 CreateWorkbook 类(class)。您需要始终使用 self 作为方法的第一个参数。 (有一些异常(exception),但它们与此处无关。)为了能够在另一种方法中使用在一种方法中定义的变量,您需要在它们前面加上 self.:

class CreateWorkbook:
def openworkbook(self, data):
self.output_filename = input('output filename:')
self.workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
self.worksheet = workbook.add_worksheet()

def closeworkbook_msg1(self, data):
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.workbook.close()
print('XLSX file named ' + output_filename + '_' + command_type +' was created')

def closeworkbook_msg2(self, data):
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.write('C1', 'item4',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.worksheet.write_column(r,3, i4)
self.workbook.close()
print('XLSX file named ' + output_filename + '_' + command_type + ' was created')

读取 csv

这没有多大意义:

f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)

with f as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')

我会把它解释为这样的:

with open(path_in + data_file) as csvfile:
read_it = list(csv.reader(csvfile, delimiter=','))

关于python - 使用继承 python34 创建交互式命令循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com