简体   繁体   English

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

[英]PyQT Read and Update TextEdit from .txt file

Here is what I am trying to do: 这是我正在尝试做的事情:

1) I am storing 10 posts at a time using the Twitter API to stream posts. 1)我使用Twitter API一次存储10条帖子,以流式发送帖子。 They are being stored into a text file called lrgDict.txt 它们被存储到名为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. 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())

What I need help with: 我需要什么帮助:

1) How do I make PyQT know when the class it is calling has finished storing the 10 posts? 1)如何在PyQT调用的班级完成10个帖子的存储后知道它?

2) Once PyQT has appended to the textEdit how do I repeat the process? 2)将PyQT附加到textEdit后,如何重复该过程?

3) This is my first Python project and any constructive criticism is warmly welcomed. 3)这是我的第一个Python项目,热烈欢迎任何建设性的批评。

Ps my eventual goal is to read in the tweets and perform a real time sentiment analysis on the posts. ps我最终的目标是阅读推文并在帖子上进行实时情绪分析。

Thanks Guys! 多谢你们!

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 您基本上需要实现信号和插槽,并且我举了一个例子来说明这一点,但是该例子是基于您的逻辑而不是使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM