-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.py
More file actions
56 lines (46 loc) · 1.43 KB
/
translator.py
File metadata and controls
56 lines (46 loc) · 1.43 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/local/bin/python
import random
from HTMLParser import HTMLParser
import requests
import re, string
class Translator(HTMLParser):
api = "http://thesaurus.com/browse/"
wordList = []
pattern = re.compile('[\W]+')
complexity = 2 #controls the complexity of the picked words from the api min=1 max=4?
def __init__(self, parent=None):
HTMLParser.__init__(self)
def translate(self, text):
text = self.pattern.sub(" ", text)
text = text.split(" ")
print "text = %s" % text
translated = ""
for word in text:
translated += self.getWord(word) + " "
translated = translated.rstrip()
translated += "."
return translated.capitalize()
def getWord(self, src):
if len(src) < 3:
return src
self.wordList = []
self.parse(src)
if len(self.wordList) > 0:
maxRand = len(self.wordList)-1
rand = random.randint(0, maxRand)
return self.wordList[rand]
else:
return src
def parse(self, src):
r = requests.get(self.api + src)
print "url = %s" % r.url
data = r.content.split("\n")
for line in data:
self.feed(line)
def handle_starttag(self, tag, attrs):
for attr in attrs:
if attr[0] == "class" and attr[1] == "common-word" and int(attrs[4][1]) >= 2:
word = attrs[0][1].replace(self.api, "")
complexity = int(attrs[4][1])
print "word = %s \t complexity = %d" % (word, complexity)
self.wordList.append(word)