PyQT从.txt文件中读取和更新TextEdit

时间:2015-11-06 15:01:19

标签: python timer pyqt

以下是我要做的事情:

1)我使用Twitter API一次存储10个帖子来传播帖子。它们存储在名为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)使用PyQT我正在调用此类来运行,检索帖子然后在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())

我需要帮助:

1)当调用的类已经完成存储10个帖子时,如何让PyQT知道?

2)一旦PyQT附加到textEdit,我该如何重复该过程?

3)这是我的第一个Python项目,任何建设性的批评都受到热烈欢迎。

P.s我的最终目标是阅读推文并对帖子进行实时情绪分析。

谢谢大家!

1 个答案:

答案 0 :(得分:1)

你基本上需要实现信号和插槽,我做了一个例子来展示这个,但是例子是基于你的逻辑而不是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()