2016年9月8日木曜日

開発環境

入門 Python 3 (Bill Lubanovic (著)、 斎藤 康毅(監修)、 長尾 高弘 (翻訳)、オライリージャパン)の11章(並行処理とネットワーク)、11.3(復習問題)、11-5を取り組んでみる。

11-5

コード(Emacs)

subscriber

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import zmq

host = 'localhost'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://{0}:{1}'.format(host, port))

topics = ['vowel', 'five']
for topic in topics:
    sub.setsockopt(zmq.SUBSCRIBE, topic.encode('utf-8'))

while True:
    topic, word = sub.recv_multipart()
    print('{0}: {1}'.format(topic.decode('utf-8'), word.decode('utf-8')))
    if word.decode('utf-8') == 'quit':
        break

publisher

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import zmq
import time
import requests
import re

host = '*'
port = 6789

ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://{0}:{1}'.format(host, port))
time.sleep(1)

req = requests.get('http://www.gutenberg.org/cache/epub/36068/pg36068.txt')
mammoth = req.text

vowel = 'vowel'.encode('utf-8')
five = 'five'.encode('utf-8')
i = 0
for word in mammoth.split():
    word = word.strip()
    if re.match(r'[aeiou]', word, re.I):
        pub.send_multipart([vowel, word.encode('utf-8')])
        i += 1
    if len(word) == 5:
        pub.send_multipart([five, word.encode('utf-8')])
        i += 1
    if i == 20:
        break

pub.send_multipart([five, 'quite'.encode('utf-8')])

入出力結果(Terminal, IPython)

$ ./sub.py &
$ ./pub.py
vowel: EBook
vowel: EBook
five: EBook
vowel: of
five: Poems
vowel: of
five: James
five: EBook
five: James
vowel: of
vowel: eBook
five: Poems
five: eBook
vowel: of
vowel: is
five: James
five: James
vowel: eBook
five: eBook
vowel: is
vowel: use
vowel: use
vowel: of
vowel: of
vowel: anyone
vowel: anyone
vowel: anywhere
vowel: anywhere
vowel: at
vowel: at
vowel: and
vowel: and
vowel: almost
vowel: almost
vowel: it,
vowel: it,
vowel: it
vowel: it
vowel: away
vowel: away
five: quite
five: quite
$

0 コメント:

コメントを投稿