我正在为一些项目学习python kivy。我有一个机器学习代码(电影评论的情感分析),我希望输出显示在一个kivy窗口。我尝试了各种各样的东西,但我还在苦苦挣扎!任何人都可以帮我解决这个问题吗?!!
**main.py**
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
import nltk
import random
from nltk.corpus import movie_reviews
import pickle
from kivy.properties import StringProperty
class Demo(GridLayout):
data = StringProperty()
def __init__(self):
super(Demo, self).__init__()
self.data = self.machine()
def machine(self):
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
all_words = []
for w in movie_reviews.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
def find_features(document):
words = set(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev,
category) in documents]
# Training and testing sets splitted up.
training_set = featuresets[:1900]
testing_set = featuresets[1900:]
classifier = nltk.NaiveBayesClassifier.train(training_set)
# Testing now.
print("Naive Bayes Algorithm accuracy percent:",
(nltk.classify.accuracy(classifier, testing_set)) * 100)
# most valuable words when it comes to positive and negative
movie reviews.
classifier.show_most_informative_features(15)
# saving the classifier
save_classifier = open("naivebayes.pickle", "wb")
pickle.dump(classifier, save_classifier)
save_classifier.close()
class DemoApp(App):
def build(self):
return Demo()
DemoApp().run()
我无法做什么来将机器学习代码的输出转换为kivy。我尝试使用boxlayout和网格布局,但我遗漏了一些东西,我不理解!
Demo.kv
<Demo>:
orientation: "vertical"
Label:
id: id_label
text: root.data
答案 0 :(得分:0)
问题在于您执行self.data = self.machine ()
但machine
方法返回None
。您应该返回要显示的字符串。
但是,如果您的函数需要相对较长的时间才能返回,那么GUI将会冻结。在这种情况下,您必须使用另一个线程或进程来执行该功能。最简单的方法是使用另一个线程和@mainthread
装饰器来更新StringProperty
(因为OpenGL相关的操作只能在主线程中完成)。
示例:
import threading
import time
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import StringProperty
from kivy.clock import mainthread
class Demo(GridLayout):
data = StringProperty()
def __init__(self):
super(Demo, self).__init__()
threading.Thread(target=self.machine).start()
def machine(self):
time.sleep(5) # Simulating blocking code.
result = "Hello StackOverflow"
self.update_label(result) # Updating label
@mainthread
def update_label(self, string):
self.data = string
class MainApp(App):
def build(self):
return Demo()
MainApp().run()