2015-11-06 51 views
1

这里是我想要做的事:PyQt的读取和更新文本编辑从.txt文件

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我打电话这个类来运行,检索的帖子,然后在文本编辑显示它们的文本文件。

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)如何让我的PyQt知道什么时候被调用类已完成存储10个职位?

2)一旦PyQT附加到文本编辑我该如何重复该过程?

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

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

谢谢!

+0

第一件事,不要在网上发布你的钥匙:) – Achayan

+0

谢谢Archayan(Y) –

回答

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()