forked from proycon/pynlpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
35 lines (26 loc) · 1.28 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
class LMClient(object):
def __init__(self,host= "localhost",port=12346,n = 0):
self.BUFSIZE = 1024
self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #Create the socket
self.socket.settimeout(120)
self.socket.connect((host, port)) #Connect to server
self.n = n
def scoresentence(self, sentence):
if self.n > 0:
raise Exception("This client instance has been set to send only " + str(self.n) + "-grams")
if isinstance(sentence,list) or isinstance(sentence,tuple):
sentence = " ".join(sentence)
self.socket.send(sentence+ "\r\n")
return float(self.socket.recv(self.BUFSIZE).strip())
def __getitem__(self, ngram):
if self.n == 0:
raise Exception("This client has been set to send only full sentence, not n-grams")
if isinstance(ngram,str) or isinstance(ngram,unicode):
ngram = ngram.split(" ")
if len(ngram) != self.n:
raise Exception("This client instance has been set to send only " + str(self.n) + "-grams.")
self.socket.send(" ".join(ngram)+ "\r\n")
return float(self.socket.recv(self.BUFSIZE).strip())