Skip to content

Commit

Permalink
Merge pull request #95 from suchow/python3
Browse files Browse the repository at this point in the history
Make compatible with Python 3
  • Loading branch information
laraross committed Sep 28, 2015
2 parents 5b8d3d1 + 2a4af04 commit 6d7e5ff
Show file tree
Hide file tree
Showing 7 changed files with 35 additions and 22 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ site/write/*
tests/corpus/newyorker/*
cache/*
proselint/cache/*
proselintMDP.sublime-project
proselintMDP.sublime-workspace
10 changes: 8 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@
import uuid
import os
import re
import urllib2
import json
try:
# For Python 3.0 and later
from urllib.parse import unquote
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import unquote


app = Flask(__name__)
cors = CORS(app)
Expand All @@ -21,7 +27,7 @@ def lint():
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))

text = urllib2.unquote(request.values['text'])
text = unquote(request.values['text'])

with open(filename, "w+") as f:
f.write(text)
Expand Down
2 changes: 1 addition & 1 deletion plugins/sublime/SublimeLinter-contrib-proselint/linter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Proselint(Linter):

"""Provides an interface to proselint."""

syntax = ('html', 'markdown', 'plain text')
syntax = ('html', 'markdown', 'plain text', 'multimarkdown')
cmd = 'proselint'
executable = None
version_args = '--version'
Expand Down
4 changes: 2 additions & 2 deletions proselint/checks/garner/a_vs_an.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def starts_with_vowel_sound(word):

def initialize():
"""Initialize the cache of pronunciations."""
print "Running initialization for garner.a_vs_an (may take a few minutes)"
print("Running initialization for garner.a_vs_an (may take a few minutes)")
from nltk.corpus import cmudict

global d
Expand All @@ -89,6 +89,6 @@ def initialize():
for i, word in enumerate(d):
starts_with_vowel_sound(word)
if not (i % 1000):
print i
print(i)

assert(d)
11 changes: 6 additions & 5 deletions proselint/checks/misc/linkchecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"""
from proselint.tools import memoize
import re
import urllib2
import urllib
from socket import error as SocketError


Expand All @@ -27,7 +27,7 @@ def check(blob):
msg = u"Broken link: {}"

regex = re.compile(
ur"""(?i)\b((?:https?://|www\d{0,3}[.]
r"""(?i)\b((?:https?://|www\d{0,3}[.]
|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+
|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)
|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019\u21a9]))""",
Expand All @@ -50,10 +50,11 @@ def check(blob):
def is_broken_link(url):
"""Check if the link return a 404 error."""
try:
request = urllib2.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
urllib2.urlopen(request).read()
request = urllib.request.Request(
url, headers={'User-Agent': 'Mozilla/5.0'})
urllib.request.urlopen(request).read()
return False
except urllib2.URLError:
except urllib.error.URLError:
return True
except SocketError:
return True
10 changes: 5 additions & 5 deletions proselint/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ def lintscore():
fullpath = os.path.join(root, f)

# Run the linter.
print "Linting {}".format(f)
print("Linting {}".format(f))
out = subprocess.check_output(
"proselint {}".format(fullpath), shell=True)

# Determine the number of errors.
regex = r".+?:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)"
num_errors = len(tuple(re.finditer(regex, out)))
print "Found {} errors.".format(num_errors)
print("Found {} errors.".format(num_errors))

# Open the document.
subprocess.call("{} {}".format("open", fullpath), shell=True)
Expand All @@ -126,7 +126,7 @@ def lintscore():
except:
pass

print "Currently {} hits and {} false alarms\n---".format(tp, fp)
print("Currently {} hits and {} false alarms\n---".format(tp, fp))

return tp * (1.0 * tp / (tp + fp)) ** 2

Expand All @@ -142,7 +142,7 @@ def proselint(
"""Define the linter command line API."""
# Return the version number.
if version:
print "v0.0.1"
print("v0.0.1")
return

# Run the intialization.
Expand All @@ -156,7 +156,7 @@ def proselint(

# In debug mode, delete the cache and *.pyc files before running.
if debug:
print "Deleting the cache..."
print("Deleting the cache...")
subprocess.call("find . -name '*.pyc' -delete", shell=True)
subprocess.call(
"rm -rfv proselint/cache > /dev/null && mkdir proselint/cache",
Expand Down
18 changes: 11 additions & 7 deletions proselint/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import inspect
import functools
import re
import hashlib
from textblob import TextBlob


def on_heroku():
Expand Down Expand Up @@ -37,23 +39,25 @@ def memoize(f):
try:
cache = shelve.open(cachepath, protocol=2)
except:
print 'Could not open cache file %s, maybe name collision' % cachepath
print('Could not open cache file %s, maybe name collision' % cachepath)
cache = None

@functools.wraps(f)
def wrapped(*args, **kwargs):
argdict = {}

# handle instance methods
if hasattr(f, '__self__'):
args = args[1:]

tempargdict = inspect.getcallargs(f, *args, **kwargs)

for k, v in tempargdict.iteritems():
argdict[k] = v
signature = f.__module__ + '.' + f.__name__

key = str(hash(frozenset(argdict.items())))
for item in tempargdict.items():
if isinstance(item, TextBlob):
signature += tempargdict['blob'].raw

key = hashlib.sha256(signature.encode('utf-8')).hexdigest()

try:
return cache[key]
Expand All @@ -64,8 +68,8 @@ def wrapped(*args, **kwargs):
return value
except TypeError:
call_to = f.__module__ + '.' + f.__name__
print ['Warning: could not disk cache call to ',
'%s; it probably has unhashable args'] % (call_to)
print('Warning: could not disk cache call to ',
'%s; it probably has unhashable args' % (call_to))
return f(*args, **kwargs)

return wrapped
Expand Down

0 comments on commit 6d7e5ff

Please sign in to comment.