找不到'cairo.Context'的外部结构转换器。

12

我又来了。以下是一个关于我正在做的名为“推特情感分析”的项目相关的代码。下面的代码主要用于显示积极和消极推文的数量,但我遇到了下面的错误。

from pyspark import SparkConf, SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import operator
import numpy as np
import matplotlib.pyplot as plt


def main():
        conf = SparkConf().setMaster("local[2]").setAppName("Streamer")
        sc = SparkContext(conf=conf)

        # Creating a streaming context with batch interval of 10 sec
        ssc = StreamingContext(sc, 10)
        ssc.checkpoint("checkpoint")
        pwords = load_wordlist("positive.txt")
        nwords = load_wordlist("negative.txt")
        counts = stream(ssc, pwords, nwords, 100)
        make_plot(counts)


def make_plot(counts):
        """
        This function plots the counts of positive and negative words for each timestep.
        """
        positiveCounts = []
        negativeCounts = []
        time = []

        for val in counts:
        positiveTuple = val[0]
        positiveCounts.append(positiveTuple[1])
        negativeTuple = val[1]
        negativeCounts.append(negativeTuple[1])

        for i in range(len(counts)):
        time.append(i)

        posLine = plt.plot(time, positiveCounts,'bo-', label='Positive')
        negLine = plt.plot(time, negativeCounts,'go-', label='Negative')
        plt.axis([0, len(counts), 0, max(max(positiveCounts), max(negativeCounts))+50])
        plt.xlabel('Time step')
        plt.ylabel('Word count')
        plt.legend(loc = 'upper left')
    plt.show()


def load_wordlist(filename):
    """ 
    This function returns a list or set of words from the given filename.
    """ 
    words = {}
    f = open(filename, 'rU')
    text = f.read()
    text = text.split('\n')
    for line in text:
        words[line] = 1
    f.close()
    return words


def wordSentiment(word,pwords,nwords):
    if word in pwords:
    return ('positive', 1)
    elif word in nwords:
    return ('negative', 1)


def updateFunction(newValues, runningCount):
    if runningCount is None:
       runningCount = 0
    return sum(newValues, runningCount) 


def sendRecord(record):
    connection = createNewConnection()
    connection.send(record)
    connection.close()


def stream(ssc, pwords, nwords, duration):
    kstream = KafkaUtils.createDirectStream(
    ssc, topics = ['twitterstream'], kafkaParams = {"metadata.broker.list": 'localhost:9092'})
    tweets = kstream.map(lambda x: x[1].encode("ascii", "ignore"))

    # Each element of tweets will be the text of a tweet.
    # We keep track of a running total counts and print it at every time step.
    words = tweets.flatMap(lambda line:line.split(" "))
    positive = words.map(lambda word: ('Positive', 1) if word in pwords else ('Positive', 0))
    negative = words.map(lambda word: ('Negative', 1) if word in nwords else ('Negative', 0))
    allSentiments = positive.union(negative)
    sentimentCounts = allSentiments.reduceByKey(lambda x,y: x+y)
    runningSentimentCounts = sentimentCounts.updateStateByKey(updateFunction)
    runningSentimentCounts.pprint()

    # The counts variable hold the word counts for all time steps
    counts = []
    sentimentCounts.foreachRDD(lambda t, rdd: counts.append(rdd.collect()))

    # Start the computation
    ssc.start() 
    ssc.awaitTerminationOrTimeout(duration)
    ssc.stop(stopGraceFully = True)

    return counts


if __name__=="__main__":
    main()

错误如下所示:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 343, in idle_draw
    self.draw()
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 336, in draw
    self.get_property("window").process_updates (False)
TypeError: Couldn't find foreign struct converter for 'cairo.Context'
4个回答

29

参见此Github讨论。例如尝试:

sudo apt-get install python-gi-cairo

非常感谢,这使得Meld重新开始工作了(它一直在发出同样的错误信息)。 - Terry Brown
15
如果您使用的是Python3,可能需要安装“python3-gi-cairo”软件包。 - Jan Spurny
2
对于 Fedora,请尝试执行dnf install python3-gobject - haolee

11

回复上面的评论,如果你用的是WSL 2、VSCode和X-server来使用GUI应用程序,那么你应该使用:

sudo apt install python3-gi-cairo

而且你就免去了更换后端的麻烦。


4
在我的情况下,python3-gi-cairo已经安装但可能存在问题。所以如果有人遇到这种情况,只需在apt安装中添加--reinstall即可解决问题。
sudo apt install --reinstall python3-gi-cairo

在这里重新安装不会破坏您的系统,因为当您卸载时(所有依赖项也将被卸载),然后再次安装它。


也帮助了我。 - lnstadrum

2
这里的问题是matplotlib的后端GTK3。我建议将其更改为适合您的工作的后端。请参见https://matplotlib.org/faq/usage_faq.html

我通常这样做

import matplotlib
matplotlib.use('Agg')

在导入matplotlib之前。 您将无法看到图像,但可以使用savefig()保存它,然后使用图像查看器打开它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接