2013-11-28 4 views
1

Я пишу скрипт python, который использует PyQt и Matplotlib для построения 2D CSV-файла. Я все еще изучаю python, поэтому им не удается работать с некоторыми из ошибок, которые я получаю. Один, в частности, что беспокоит меня этоПроблема с использованием np.genfromtxt в методе python

Ошибка:

Traceback (most recent call last): File "C:/Users/jonesza/Documents/Python Scripts/2D-Graph/Qt_2D_Plot.py", line 62, in update_graph l, v = self.parse_file(self.mpllineEdit.text()) File "C:/Users/jonesza/Documents/Python Scripts/2D-Graph/Qt_2D_Plot.py", line 53, in parse_file names=['time','temperature']) File "C:\WinPython\python-2.7.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 1356, in genfromtxt first_values = split_line(first_line) File "C:\WinPython\python-2.7.5.amd64\lib\site-packages\numpy\lib_iotools.py", line 208, in _delimited_splitter line = line.strip(asbytes(" \r\n")) AttributeError: 'QString' object has no attribute 'strip'

Исходный код:

# used to parse files more easily 
from __future__ import with_statement 

# Numpy module 
import numpy as np 

# for command-line arguments 
import sys 

# Qt4 bindings for core Qt functionalities (non-Gui) 
from PyQt4 import QtCore 
# Python Qt4 bindings for GUI objects 
from PyQt4 import QtGui 

# import the MainWindow widget from the converted .ui files 
from qtdesigner import Ui_MplMainWindow 

class DesignerMainWindow(QtGui.QMainWindow, Ui_MplMainWindow): 
    """Customization for Qt Designer created window""" 
    def __init__(self, parent = None): 
     # initialization of the super class 
     super(DesignerMainWindow, self).__init__(parent) 
     # setup the GUI --> function generated by pyuic4 
     self.setupUi(self) 

     # connect the signals with the slots 
     QtCore.QObject.connect(self.mplpushButton, QtCore. 
SIGNAL("clicked()"), self.update_graph) 
     QtCore.QObject.connect(self.mplactionOpen, QtCore. 
SIGNAL("triggered()"), self.select_file) 
     QtCore.QObject.connect(self.mplactionQuit, QtCore. 
SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) 

    def select_file(self): 
     """opens a file select dialog""" 
     # open the dialog and get the selected file 
     file = QtGui.QFileDialog.getOpenFileName() 
     # if a file is selected 
     if file: 
      # update the lineEdit text with the selected filename 
      self.mpllineEdit.setText(file) 

    def parse_file(self, filename): 
     """gets first two columns from .csv uploaded""" 
     #import data from .csv 
     data = np.genfromtxt(filename, delimiter=',', 
            names=['time','temperature']) 
     x = data['time'] 
     y = data['temperature'] 

     return x,y 

    def update_graph(self):  
     """Updates the graph with new letteers frequencies""" 
     # get the axes for the 2D graph 
     l, v = self.parse_file(self.mpllineEdit.text()) 
     # clear the Axes 
     self.mpl.canvas.ax.clear() 
     # plot the axes 
     self.mpl.canvas.ax.plot(l,v) 
     # force an image redraw 
     self.mpl.canvas.draw() 

# create the GUI application 
app = QtGui.QApplication(sys.argv) 
# instantiate the main window 
dmw = DesignerMainWindow() 
# show it 
dmw.show() 
# start the Qt main loop execution, exiting from this script 
# with the same return code of Qt application 
sys.exit(app.exec_()) 

Спасибо заранее за любую помощь.

+0

Выполняется ли 'parse_file' в простой оболочке Python с' import numpy'? Ошибка «Qstring» указывает на что-то, что связано с Qt. – hpaulj

+0

есть. Я добавил больше для дополнительного контекста выше. – user3044129

ответ

1

Я предполагаю, что self.mpllineEdit.text() создает QString. Вам нужно исследовать либо в документации PyQt, либо в интерактивной оболочке, какие методы у нее есть, и если вам нужно что-то сделать, чтобы преобразовать ее в обычную строку Python. genfromtxt пытается разбить эту строку на строки, а затем удалить строки, заканчивающиеся символами, поэтому он может проанализировать строку.

Try:

self.parse_file(str(self.mpllineEdit.text())) 

Это может преобразовать Qstring в обычную строку Python.

+0

Спасибо! что это решило! – user3044129

Смежные вопросы