Простая программа на Python для чтения. файл gcode

Я совершенно новичок в Python, и я хотел создать простой скрипт, который найдет мне определенное значение в файле и затем выполнит некоторые вычисления с ним.

Итак, у меня есть файл.gcode (это файл с тысячами строк для 3D-принтера, но его можно открыть любым простым текстовым редактором). Я хотел создать простую программу на Python, в которой при запуске открывается простой графический интерфейс с кнопкой, предлагающей выбрать файл.gcode. Затем, после открытия файла, я бы хотел, чтобы программа нашла конкретную строку

; использованная нить = 22900,5 мм (55,1 см3)

(выше указан точный формат строки из файла) и извлеките из него значение 55.1. Позже я хотел бы сделать несколько простых расчетов с этим значением. До сих пор я сделал простой графический интерфейс и кнопку с опцией открытия файла, но я застрял на том, как получить это значение как число (чтобы его можно было использовать в уравнениях позже) из этого файла.

Я надеюсь, что объяснил свою проблему достаточно ясно, чтобы кто-нибудь мог мне помочь:) Заранее спасибо за помощь!

Мой код до сих пор:

from tkinter import *
import re




# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):

    # Define settings upon initialization. Here you can specify
def __init__(self, master=None):

        # parameters that you want to send through the Frame class. 
Frame.__init__(self, master)   

        #reference to the master widget, which is the tk window                 
self.master = master

        #with that, we want to then run init_window, which doesn't yet exist
self.init_window()

    #Creation of init_window
def init_window(self):

        # changing the title of our master widget      
self.master.title("Used Filament Data")

        # allowing the widget to take the full space of the root window
self.pack(fill=BOTH, expand=1)

        # creating a menu instance
menu = Menu(self.master)
self.master.config(menu=menu)

        # create the file object)
file = Menu(menu)

        # adds a command to the menu option, calling it exit, and the
        # command it runs on event is client_exit
file.add_command(label="Exit", command=self.client_exit)

        #added "file" to our menu
menu.add_cascade(label="File", menu=file)

        #Creating the button
quitButton = Button(self, text="Load GCODE",command=self.read_gcode)
quitButton.place(x=0, y=0)

def get_filament_value(self, filename):
with open(filename, 'r') as f_gcode:
data = f_gcode.read()
re_value = re.search('filament used = .*? \(([0-9.]+)', data)

if re_value:
value = float(re_value.group(1))
else:
print 'filament not found in {}'.format(root.fileName)
value = 0.0
return value

print get_filament_value('test.gcode') 

def read_gcode(self):
root.fileName = filedialog.askopenfilename( filetypes = ( ("GCODE files", "*.gcode"),("All files", "*.*") ) )
self.value = self.get_filament_value(root.fileName)

def client_exit(self):
exit()





# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()

root.geometry("400x300")

#creation of an instance
app = Window(root)

#mainloop 
root.mainloop()  

1 ответ

Решение

Вы можете использовать регулярное выражение, чтобы найти соответствующую строку в файле gcode. Следующая функция загружает весь файл gcode и выполняет поиск. Если он найден, значение возвращается как число с плавающей запятой.

import re

def get_filament_value(filename):
    with open(filename, 'r') as f_gcode:
        data = f_gcode.read()
        re_value = re.search('filament used = .*? \(([0-9.]+)', data)

        if re_value:
            value = float(re_value.group(1))
        else:
            print('filament not found in {}'.format(filename))
            value = 0.0
        return value

print(get_filament_value('test.gcode'))

Который для вашего файла должен отображаться:

55.1

Итак, ваш оригинальный код будет выглядеть примерно так:

from tkinter import *
import re

# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):

    # Define settings upon initialization. Here you can specify
    def __init__(self, master=None):

        # parameters that you want to send through the Frame class. 
        Frame.__init__(self, master)   

        #reference to the master widget, which is the tk window                 
        self.master = master

        #with that, we want to then run init_window, which doesn't yet exist
        self.init_window()

    #Creation of init_window
    def init_window(self):

        # changing the title of our master widget      
        self.master.title("Used Filament Data")

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a menu instance
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # create the file object)
        file = Menu(menu)

        # adds a command to the menu option, calling it exit, and the
        # command it runs on event is client_exit
        file.add_command(label="Exit", command=self.client_exit)

        #added "file" to our menu
        menu.add_cascade(label="File", menu=file)

        #Creating the button
        quitButton = Button(self, text="Load GCODE",command=self.read_gcode)
        quitButton.place(x=0, y=0)

    # Load the gcode file in and extract the filament value
    def get_filament_value(self, fileName):
        with open(fileName, 'r') as f_gcode:
            data = f_gcode.read()
            re_value = re.search('filament used = .*? \(([0-9.]+)', data)

            if re_value:
                value = float(re_value.group(1))
                print('filament value is {}'.format(value))
            else:
                value = 0.0
                print('filament not found in {}'.format(fileName))
        return value

    def read_gcode(self):
        root.fileName = filedialog.askopenfilename(filetypes = (("GCODE files", "*.gcode"), ("All files", "*.*")))
        self.value = self.get_filament_value(root.fileName)

    def client_exit(self):
        exit()

# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()

root.geometry("400x300")

#creation of an instance
app = Window(root)

#mainloop 
root.mainloop() 

Это сохранит результат как float в переменную класса с именем value,

Другие вопросы по тегам