【问题标题】:Multi threading using Python and pymongo使用 Python 和 pymongo 的多线程
【发布时间】:2015-08-03 16:46:00
【问题描述】:

您好,我正在寻找一个程序,该程序将对推文进行正分类和负分类,对已保存在 mongodb 中并且一旦分类的公司的推文进行分类,以根据当时的结果更新整数。

我编写了代码使这成为可能,但我想对程序进行多线程处理,但我在 python 中没有这方面的经验,并且一直在尝试遵循教程但没有运气,因为程序只是启动和退出而没有通过任何代码。

如果有人可以帮助我,将不胜感激。该程序的代码和预期的多线程如下。

from textblob.classifiers import NaiveBayesClassifier
import pymongo
import datetime
from threading import Thread

train = [
('I love this sandwich.', 'pos'),
('This is an amazing place!', 'pos'),
('I feel very good about these beers.', 'pos'),
('This is my best work.', 'pos'),
("What an awesome view", 'pos'),
('I do not like this restaurant', 'neg'),
('I am tired of this stuff.', 'neg'),
("I can't deal with this", 'neg'),
('He is my sworn enemy!', 'neg'),
('My boss is horrible.', 'neg'),
(':)', 'pos'),
(':(', 'neg'),
('gr8', 'pos'),
('gr8t', 'pos'),
('lol', 'pos'),
('bff', 'neg'),
]

test = [
'The beer was good.',
'I do not enjoy my job',
"I ain't feeling dandy today.",
"I feel amazing!",
'Gary is a friend of mine.',
"I can't believe I'm doing this.",
]

filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple',   'Google', 'Amazon', 'EBay', 'Diageo',
              'General Motors', 'General Electric', 'Telefonica', 'Rolls Royce', 'Walmart', 'HSBC', 'BP',
              'Investec', 'WWE', 'Time Warner', 'Santander Group']

# Create pos/neg counter variables for each company using dicts
vars = {}
for word in filterKeywords:
vars[word + "SentimentOverall"] = 0


# Initialising the classifier
cl = NaiveBayesClassifier(train)


class TrainingClassification():
    def __init__(self):
        #creating the mongodb connection
        try:
            conn = pymongo.MongoClient('localhost', 27017)
            print "Connected successfully!!!"
            global db
            db = conn.TwitterDB
        except pymongo.errors.ConnectionFailure, e:
            print "Could not connect to MongoDB: %s" % e

        thread1 = Thread(target=self.apple_thread, args=())
        thread1.start()
        thread1.join()
        print "thread finished...exiting"

    def apple_thread(self):
        appleSentimentText = []
        for record in db.Apple.find():
            if record.get('created_at'):
                created_at = record.get('created_at')
                dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')
                if record.get('text') and dt > datetime.today():
                    appleSentimentText.append(record.get("text"))
        for targetText in appleSentimentText:
            classificationApple = cl.classify(targetText)
            if classificationApple == "pos":
                vars["AppleSentimentOverall"] = vars["AppleSentimentOverall"] + 1
            elif classificationApple == "neg":
                vars["AppleSentimentOverall"] = vars["AppleSentimentOverall"] - 1

【问题讨论】:

  • 你需要像这样初始化TrainingClassification.]:TrainingClassification(conn)。不过,我不知道conn 是什么。
  • 那位是要删除的对不起,我会更新我的问题。

标签: python multithreading mongodb twitter pymongo


【解决方案1】:

您的代码的主要问题在这里:

thread1.start()
thread1.join()

当您在线程上调用 join 时,它具有使当前正在运行的线程(在您的情况下为主线程)等待直到线程完成(此处为 thread1)的效果。所以你可以看到你的代码实际上不会更快。它只是启动一个线程并等待它。由于线程创建,它实际上会稍微慢一些。

这是进行多线程处理的正确方法:

thread1.start()
thread2.start()
thread1.join()
thread2.join()

在这段代码中,线程 1 和 2 都将并行运行。

重要提示:请注意,在 Python 中,它是一种“模拟”并行化。因为 Python 的核心不是线程安全的(主要是因为它进行垃圾收集的方式),所以它使用 GIL(全局解释器锁),因此一个进程中的所有线程只在一个核心上运行。 如果您热衷于使用真正的并行化(例如,如果您的 2 个线程是 CPU 限制而不是 I/O 限制),请查看多处理模块。

【讨论】:

  • 对不起,我已经离开电脑几天了。谢谢,现在就尝试使用它,让你知道它是怎么回事!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多