PyQT Read and Update TextEdit from .txt file

2019-08-09 23:15发布

问题:

Here is what I am trying to do:

1) I am storing 10 posts at a time using the Twitter API to stream posts. They are being stored into a text file called lrgDict.txt

import tweepy,datetime, sys, os, time, pprint
from tweepy.api import API

consumer_key ""
consumer_secret=""
access_token=""
access_token_secret=""

key = tweepy.OAuthHandler(consumer_key, consumer_secret)
key.set_access_token(access_token, access_token_secret)

class TwitterAPIStreamDictionary(tweepy.StreamListener):
    output = {}

    def __init__(self, api=None):
        print(datetime.datetime.time(datetime.datetime.now()))
        self.api = api or API()
        self.j = 0
        self.k = 10


    def on_status(self, status):

        self.output[status.id] = {
            'text':status.text.encode('utf-8'),
            'user':status.user.screen_name.encode('utf-8'),
            'place':status.place,
            'location':status.user.location}

        output = open('dictLrg.txt', 'ab')
        for tweet in self.output:
            output.write( "\n".encode(encoding='utf-8') + "User: ".encode(encoding='utf-8') + self.output[tweet]['user'] + "\n".encode(encoding='utf-8') + "Text: ".encode(encoding='utf-8') + self.output[tweet]['text'] + "\n".encode(encoding='utf-8'))
            pprint.pprint("User: ".encode(encoding='utf-8') + self.output[tweet]['user'] + " Text: ".encode(encoding='utf-8') + self.output[tweet]['text'])
            output.flush()
        output.close()

        if self.j < self.k:
            self.j = self.j + 1
            return True

        else:
            print('Search Complete')
            print(datetime.datetime.time(datetime.datetime.now()))
            return False

    def on_error(self, status_code):
        print(status_code)
        return True

    def on_timeout(self):
        print('Timeout')
        return True

2) Using PyQT I am calling this class to run, retrieve the posts and then display them in the TextEdit.

from PyQt4 import QtCore, QtGui
import sys, tweepy, TwitterAPIStreamSentiment, time, os
from tweepy.api import API

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)

    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(800, 600)
        self.verticalLayout_2 = QtGui.QVBoxLayout(Form)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.searchText = QtGui.QLineEdit(Form)
        self.searchText.setObjectName(_fromUtf8("searchText"))
        self.verticalLayout.addWidget(self.searchText)
        self.submitButton = QtGui.QPushButton(Form)
        self.submitButton.setObjectName(_fromUtf8("submitButton"))
        self.verticalLayout.addWidget(self.submitButton)
        self.resultsText = QtGui.QPlainTextEdit (Form)
        self.resultsText.setReadOnly(True)
        self.resultsText.setObjectName(_fromUtf8("resultsText"))
        self.verticalLayout.addWidget(self.resultsText)
        self.verticalLayout_2.addLayout(self.verticalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.submitButton.setText(_translate("Form", "Submit", None))
        self.submitButton.clicked.connect(self.printResults)

    def printResults(self):
        stream = tweepy.streaming.Stream(TwitterAPIStreamSentiment.key, TwitterAPIStreamSentiment.TwitterAPIStreamDictionary())
        stream.filter(track=[str(self.searchText.text())], async='true')
        file = open('dictLrg.txt', 'r', encoding="utf8").read()
        QtCore.QTimer.singleShot(15000, lambda: self.resultsText.insertPlainText(file))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_Form()
    ex.show()
    sys.exit(app.exec())

What I need help with:

1) How do I make PyQT know when the class it is calling has finished storing the 10 posts?

2) Once PyQT has appended to the textEdit how do I repeat the process?

3) This is my first Python project and any constructive criticism is warmly welcomed.

P.s my eventual goal is to read in the tweets and perform a real time sentiment analysis on the posts.

Thanks Guys!

回答1:

You basically need to implement signals and slots and I made a example to show this, but example is based on your logic but not with twiter api

from PyQt4 import QtGui, QtCore
import sys

class FetchData(QtCore.QObject):
    fetchFinished = QtCore.pyqtSignal(str)
    def __init__(self, *args):
        super(FetchData, self).__init__(*args)

    @QtCore.pyqtSlot()
    def run(self, searchStr):
        rtString = "Some data from no where : %s" % searchStr
        self.fetchFinished.emit(str(rtString))

class BASEGUICLS(QtGui.QDialog):
    def __init__(self,parent=None):
        super(BASEGUICLS, self).__init__(parent)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.searchString = QtGui.QLineEdit()
        self.resultsText = QtGui.QPlainTextEdit()
        self.fetchButton = QtGui.QPushButton("Fetch")
        self.stopButton = QtGui.QPushButton("Stop")
        self.verticalLayout.addWidget(self.searchString)
        self.verticalLayout.addWidget(self.resultsText)
        self.verticalLayout.addWidget(self.fetchButton)
        self.verticalLayout.addWidget(self.stopButton)
        self.setLayout(self.verticalLayout)
        self.fetchData = FetchData()
        self.fetchData.fetchFinished.connect(self.updateResult)
        self.fetchButton.clicked.connect(self.getData)
        self.stopButton.clicked.connect(self.stopFetch)
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.refreshResult)

    def getData(self):
        self.timer.start(500)

    def refreshResult(self):
        searchStr = str(self.searchString.text())
        if not searchStr:
            self.stopFetch()
            raise RuntimeError("Missing Search String")
        self.fetchData.run(searchStr)

    def stopFetch(self):
        self.timer.stop()

    def updateResult(self, value):
        self.resultsText.appendPlainText(value)


def main():
    app = QtGui.QApplication(sys.argv)
    ex = BASEGUICLS(None)
    ex.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()