Remove deprecated string module functions (#1223)

* 1194: Review assignments of range in Python code

Task-Url: https://github.com/rdkit/rdkit/issues/1194
Either wrapped the range expression into a list or made sure that the
code is working with a range object.

* Removed use of deprecated string module functions
This commit is contained in:
gedeck
2016-12-21 11:02:03 -05:00
committed by Greg Landrum
parent 92c21f9a8a
commit bb71cd430d
16 changed files with 100 additions and 105 deletions

2
.gitignore vendored
View File

@@ -49,6 +49,8 @@ __pycache__/
/Code/GraphMol/Depictor/test_data/collisions.out.sdf
/Code/GraphMol/Depictor/test_data/first_200.out.sdf
/Code/GraphMol/Depictor/test_data/test1.out.sdf
/Code/GraphMol/Depictor/test_data/constrainedCoords.out.sdf
/Code/GraphMol/FileParsers/test_data/blah.sdf
/Code/GraphMol/FileParsers/test_data/cdk2_stereo.sdf

View File

@@ -16,7 +16,6 @@ piddlePDF calls pdfgen and offers a high-level interface.
from __future__ import print_function
import os
import sys
import string
import time
import tempfile
from types import *
@@ -264,7 +263,7 @@ class OutputGrabber:
self.data.append(x)
def getData(self):
return string.join(self.data)
return ' '.join(self.data)
def close(self):
sys.stdout = self.oldoutput
@@ -321,9 +320,9 @@ class PDFCatalog(PDFObject):
"requires RefPages and RefOutlines set"
def __init__(self):
self.template = string.join([
self.template = LINEEND.join([
'<<', '/Type /Catalog', '/Pages %d 0 R', '/Outlines %d 0 R', '>>'
], LINEEND)
])
def save(self, file):
file.write(self.template % (self.RefPages, self.RefOutlines) + LINEEND)
@@ -344,10 +343,10 @@ class PDFInfo(PDFObject):
def save(self, file):
file.write(
string.join([
LINEEND.join([
"<</Title (%s)", "/Author (%s)", "/CreationDate (D:%s)", "/Producer (PDFgen)",
"/Subject (%s)", ">>"
], LINEEND) % (pdfutils._escape(self.title), pdfutils._escape(self.author), self.datestr,
]) % (pdfutils._escape(self.title), pdfutils._escape(self.author), self.datestr,
pdfutils._escape(self.subject)) + LINEEND)
@@ -355,7 +354,7 @@ class PDFOutline(PDFObject):
"null outline, does nothing yet"
def __init__(self):
self.template = string.join(['<<', '/Type /Outlines', '/Count 0', '>>'], LINEEND)
self.template = LINEEND.join(['<<', '/Type /Outlines', '/Count 0', '>>'])
def save(self, file):
file.write(self.template + LINEEND)
@@ -373,7 +372,7 @@ class PDFPageCollection(PDFObject):
lines.append(str(page) + ' 0 R ')
lines.append(']')
lines.append('>>')
text = string.join(lines, LINEEND)
text = LINEEND.join(lines)
file.write(text + LINEEND)
@@ -391,7 +390,7 @@ class PDFPage(PDFObject):
self.pageTransitionString = '' # presentation effects
# editors on different systems may put different things in the line end
# without me noticing. No triple-quoted strings allowed!
self.template = string.join([
self.template = LINEEND.join([
'<<',
'/Type /Page',
'/Parent %(parentpos)d 0 R',
@@ -404,8 +403,7 @@ class PDFPage(PDFObject):
'/Contents %(contentspos)d 0 R',
'%(transitionString)s',
'>>'
],
LINEEND)
])
def setCompression(self, onoff=0):
"Turns page compression on or off"
@@ -428,8 +426,8 @@ class PDFPage(PDFObject):
self.drawables = []
def setStream(self, data):
if type(data) is ListType:
data = string.join(data, LINEEND)
if isinstance(data, (list, tuple)):
data = LINEEND.join(data, LINEEND)
self.stream.setStream(data)
@@ -477,13 +475,13 @@ class PDFImage(PDFObject):
# sample one while developing. Currently, images go in a literals
def save(self, file):
file.write(
string.join([
LINEEND.join([
'<<', '/Type /XObject', '/Subtype /Image', '/Name /Im0', '/Width 24', '/Height 23',
'/BitsPerComponent 1', '/ColorSpace /DeviceGray', '/Filter /ASCIIHexDecode', '/Length 174',
'>>', 'stream', '003B00 002700 002480 0E4940 114920 14B220 3CB650',
'75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC',
'B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800', '1E1800 1FF800>', 'endstream', 'endobj'
], LINEEND) + LINEEND)
]) + LINEEND)
class PDFType1Font(PDFObject):
@@ -491,10 +489,10 @@ class PDFType1Font(PDFObject):
def __init__(self, key, font):
self.fontname = font
self.keyname = key
self.template = string.join([
self.template = LINEEND.join([
'<<', '/Type /Font', '/Subtype /Type1', '/Name /%s', '/BaseFont /%s',
'/Encoding /MacRomanEncoding', '>>'
], LINEEND)
])
def save(self, file):
file.write(self.template % (self.keyname, self.fontname) + LINEEND)

View File

@@ -53,7 +53,6 @@ Progress Reports:
from __future__ import print_function
import os
import sys
import string
import time
import tempfile
from io import StringIO
@@ -64,6 +63,7 @@ from . import pdfutils
from . import pdfdoc
from . import pdfmetrics
from . import pdfgeom
from rdkit.six import string_types
class PDFError(ValueError):
@@ -172,8 +172,8 @@ class Canvas:
"""PDF escapes are like Python ones, but brackets need slashes before them too.
Use Python's repr function and chop off the quotes first"""
s = repr(s)[1:-1]
s = string.replace(s, '(', '\(')
s = string.replace(s, ')', '\)')
s = s.replace('(', '\(')
s = s.replace(')', '\)')
return s
#info functions - non-standard
@@ -515,11 +515,11 @@ class Canvas:
def setDash(self, array=[], phase=0):
"""Two notations. pass two numbers, or an array and phase"""
if type(array) == IntType or type(array) == FloatType:
if isinstance(array, (int, float)):
self._code.append('[%s %s] 0 d' % (array, phase))
elif type(array) == ListType or type(array) == TupleType:
elif isinstance(array, (list, tuple)):
assert phase <= len(array), "setDash phase must be l.t.e. length of array"
textarray = string.join(map(str, array))
textarray = ' '.join(map(str, array))
self._code.append('[%s] %s d' % (textarray, phase))
def setFillColorRGB(self, r, g, b):
@@ -576,8 +576,7 @@ class Canvas:
return
self._currentPageHasImages = 1
if type(image) == StringType:
if isinstance(image, string_types):
if os.path.splitext(image)[1] in ['.jpg', '.JPG']:
#directly process JPEG files
#open file, needs some error handling!!
@@ -615,12 +614,12 @@ class Canvas:
cachedname = os.path.splitext(image)[0] + '.a85'
imagedata = open(cachedname, 'rb').readlines()
#trim off newlines...
imagedata = map(string.strip, imagedata)
imagedata = [s.strip() for s in imagedata]
#parse line two for width, height
words = string.split(imagedata[1])
imgwidth = string.atoi(words[1])
imgheight = string.atoi(words[3])
words = imagedata[1].split()
imgwidth = int(words[1])
imgheight = int(words[3])
else:
#PIL Image
#work out all dimensions
@@ -789,7 +788,7 @@ class Canvas:
return
self._pageTransitionString = (
('/Trans <</D %d /S /%s ' % (duration, effectname)) + string.join(args, ' ') + ' >>')
('/Trans <</D %d /S /%s ' % (duration, effectname)) + ' '.join(args) + ' >>')
class PDFPathObject:
@@ -808,7 +807,7 @@ class PDFPathObject:
def getCode(self):
"pack onto one line; used internally"
return string.join(self._code, ' ')
return ' '.join(self._code)
def moveTo(self, x, y):
self._code.append('%0.4f %0.4f m' % (x, y))
@@ -892,7 +891,7 @@ class PDFTextObject:
def getCode(self):
"pack onto one line; used internally"
self._code.append('ET')
return string.join(self._code, ' ')
return ' '.join(self._code)
def setTextOrigin(self, x, y):
if self._canvas.bottomup:
@@ -1021,13 +1020,11 @@ class PDFTextObject:
since this may be indented, by default it trims whitespace
off each line and from the beginning; set trim=0 to preserve
whitespace."""
if type(stuff) == StringType:
lines = string.split(string.strip(stuff), '\n')
if isinstance(stuff, string_types):
lines = stuff.strip().split('\n')
if trim == 1:
lines = map(string.strip, lines)
elif type(stuff) == ListType:
lines = stuff
elif type(stuff) == TupleType:
lines = [s.strip() for s in lines]
elif isinstance(stuff, (tuple, list)):
lines = stuff
else:
raise ValueError("argument to textlines must be string, list or tuple")

View File

@@ -3,28 +3,28 @@
be used for any other PIDDLE back ends or packages which use the standard
Type 1 postscript fonts.
Its main function is to let you work out the width of strings; it exposes a
single function, stringwidth(text, fontname), which works out the width of a
Its main function is to let you work out the width of strings; it exposes a
single function, stringwidth(text, fontname), which works out the width of a
string in the given font. This is an integer defined in em-square units - each
character is defined in a 1000 x 1000 box called the em-square - for a 1-point high
character. So to convert to points, multiply by 1000 and then by point size.
The AFM loading stuff worked for me but is not being heavily tested, as pre-canning
the widths for the standard 14 fonts in Acrobat Reader is so much more useful. One
could easily extend it to get the exact bounding box for each characterm useful for
could easily extend it to get the exact bounding box for each characterm useful for
kerning.
The ascent_descent attribute of the module is a dictionary mapping font names
(with the proper Postscript capitalisation) to ascents and descents. I ought
to sort out the fontname case issue and the resolution of PIDDLE fonts to
to sort out the fontname case issue and the resolution of PIDDLE fonts to
Postscript font names within this module, but have not yet done so.
13th June 1999
"""
from __future__ import print_function
import string, os
import os
StandardEnglishFonts = [
'Courier', 'Courier-Bold', 'Courier-Oblique', 'Courier-BoldOblique', 'Helvetica',
@@ -251,25 +251,25 @@ def parseAFMfile(filename):
metriclines = []
between = 0
for line in alllines:
if string.find(string.lower(line), 'endcharmetrics') > -1:
if 'endcharmetrics' in line.lower():
between = 0
break
if between:
metriclines.append(line)
if string.find(string.lower(line), 'startcharmetrics') > -1:
if 'startcharmetrics' in line.lower():
between = 1
# break up - very shaky assumption about array size
widths = [0] * 255
for line in metriclines:
chunks = string.split(line, ';')
chunks = line.split(';')
(c, cid) = string.split(chunks[0])
(wx, width) = string.split(chunks[1])
(c, cid) = chunks[0].split()
(wx, width) = chunks[1].split()
#(n, name) = string.split(chunks[2])
#(b, x1, y1, x2, y2) = string.split(chunks[3])
widths[string.atoi(cid)] = string.atoi(width)
widths[int(cid)] = int(width)
# by default, any empties should get the width of a space
for i in range(len(widths)):

View File

@@ -2,7 +2,6 @@
# compression, and some constants
from __future__ import print_function
import os
import string
from io import StringIO
from rdkit.six import string_types
import glob
@@ -47,7 +46,7 @@ def cacheImageFile(filename):
#save it to a file
cachedname = os.path.splitext(filename)[0] + '.a85'
f = open(cachedname, 'wb')
f.write(string.join(code, LINEEND) + LINEEND)
f.write(LINEEND.join(code) + LINEEND)
f.close()
print('cached image as %s' % cachedname)
@@ -96,18 +95,18 @@ def _escape(s):
need slashes before them too. Use Python's repr function
and chop off the quotes first"""
s = repr(s)[1:-1]
s = string.replace(s, '(', '\(')
s = string.replace(s, ')', '\)')
s = s.replace('(', '\(')
s = s.replace(')', '\)')
return s
def _normalizeLineEnds(text, desired=LINEEND):
"""ensures all instances of CR, LF and CRLF end up as the specified one"""
unlikely = '\000\001\002\003'
text = string.replace(text, '\015\012', unlikely)
text = string.replace(text, '\015', unlikely)
text = string.replace(text, '\012', unlikely)
text = string.replace(text, unlikely, desired)
text = text.replace('\015\012', unlikely)
text = text.replace('\015', unlikely)
text = text.replace('\012', unlikely)
text = text.replace(unlikely, desired)
return text
@@ -126,7 +125,7 @@ def _AsciiHexEncode(input):
def _AsciiHexDecode(input):
"Not used except to provide a test of the preceding"
#strip out all whitespace
stripped = string.join(string.split(input), '')
stripped = ''.join(input.split(), '')
assert stripped[-1] == '>', 'Invalid terminator for Ascii Hex Stream'
stripped = stripped[:-1] #chop off terminator
assert len(stripped) % 2 == 0, 'Ascii Hex stream has odd number of bytes'
@@ -226,13 +225,13 @@ def _AsciiBase85Decode(input):
trip is essential for testing."""
outstream = StringIO()
#strip all whitespace
stripped = string.join(string.split(input), '')
stripped = ''.join(input.split(), '')
#check end
assert stripped[-2:] == '~>', 'Invalid terminator for Ascii Base 85 Stream'
stripped = stripped[:-2] #chop off terminator
#may have 'z' in it which complicates matters - expand them
stripped = string.replace(stripped, 'z', '!!!!!')
stripped = stripped.replace('z', '!!!!!')
# special rules apply if not a multiple of five bytes.
whole_word_count, remainder_size = divmod(len(stripped), 5)
#print '%d words, %d leftover' % (whole_word_count, remainder_size)
@@ -303,7 +302,7 @@ def _wrap(input, columns=60):
i = i + 1
pos = columns * i
return string.join(output, LINEEND)
return LINEEND.join(output)
def _AsciiBase85Test(text='What is the average velocity of a sparrow?'):

View File

@@ -16,7 +16,6 @@ self.pdf which offers numerous lower-level drawing routines.
#pylint: disable=E1103,W0311,E1101
from __future__ import print_function
#standard python library modules
import string
from . import pdfmetrics
import glob
import os
@@ -24,6 +23,7 @@ import types
from math import sin, cos, pi, ceil
# app specific
from rdkit.six import string_types
from rdkit.sping import pagesizes
from rdkit.sping.pid import *
from . import pdfgen
@@ -174,7 +174,7 @@ class PDFCanvas(Canvas):
if hasattr(file, 'write'):
self.pdf.save(fileobj=file)
elif isinstance(file, types.StringType):
elif isinstance(file, string_types):
self.pdf.save(filename=file)
else:
self.pdf.save()
@@ -232,8 +232,8 @@ class PDFCanvas(Canvas):
"""PDF escapes are like Python ones, but brackets need slashes before them too.
Use Python's repr function and chop off the quotes first"""
s = repr(s)[1:-1]
s = string.replace(s, '(', '\(')
s = string.replace(s, ')', '\)')
s = s.replace('(', '\(')
s = s.replace(')', '\)')
return s
def resetDefaults(self):
@@ -338,9 +338,9 @@ class PDFCanvas(Canvas):
if col != transparent:
if '\n' in s or '\r' in s:
#normalize line ends
s = string.replace(s, '\r\n', '\n')
s = string.replace(s, '\n\r', '\n')
lines = string.split(s, '\n')
s = s.replace('\r\n', '\n')
s = s.replace('\n\r', '\n')
lines = s.split('\n')
else:
lines = [s]
fnt = font or self.defaultFont

View File

@@ -2,7 +2,6 @@
# Christopher Lee clee@users.sourceforge.net
# based upon pdfmetrics.py by Andy Robinson
import string
from . import fontinfo
from . import latin1MetricsCache

View File

@@ -3,7 +3,6 @@
#
DefaultFace = 'times'
import string
# these are the required fonts for piddle
PidLegalFonts = {"courier": "courier", # note: keys are lowercased

View File

@@ -37,7 +37,7 @@ from rdkit.sping.pid import *
from rdkit.sping.PDF import pidPDF, pdfmetrics
from reportlab.lib import colors
from reportlab.graphics import shapes
import string, os, types
import os, types
from math import *

View File

@@ -46,7 +46,6 @@ Greg Landrum (greglandrum@earthlink.net) 3/10/2000
from rdkit.sping.pid import *
from rdkit.sping.PDF import pdfmetrics # for font info
import string
from rdkit import six
from math import *
@@ -160,19 +159,19 @@ class SVGCanvas(Canvas):
if font.face is None:
font.__dict__['face'] = 'sansserif' # quick hack -cwl
if isinstance(font.face, six.string_types):
if len(string.split(font.face)) > 1:
if len(font.face.split()) > 1:
familyStr = '\'%s\'' % font.face
else:
familyStr = font.face
else:
face = font.face[0]
if len(string.split(face)) > 1:
if len(face.split()) > 1:
familyStr = '\'%s\'' % (face)
else:
familyStr = face
for i in xrange(1, len(font.face)):
face = font.face[i]
if len(string.split(face)) > 1:
if len(face.split()) > 1:
familyStr = ', \'%s\'' % (face)
else:
familyStr = familyStr + ', %s' % face
@@ -526,7 +525,7 @@ class SVGCanvas(Canvas):
xLoc = x
yLoc = y
outStr += '<svg:g>'
lines = string.split(s, '\n')
lines = s.split('\n')
lineHeight = self.fontHeight(font)
yP = yLoc
for line in lines:

View File

@@ -19,7 +19,6 @@ You can find the latest version of this file:
import Tkinter, tkFont
tk = Tkinter
import rdkit.sping.pid
import string
__version__ = "0.3"
__date__ = "April 8, 1999"

View File

@@ -182,9 +182,9 @@ class PiddleWxDc(sping_pid.Canvas):
if '\n' in s or '\r' in s:
#normalize line ends
s = string.replace(s, '\r\n', '\n')
s = string.replace(s, '\n\r', '\n')
lines = string.split(s, '\n')
s = s.replace('\r\n', '\n')
s = s.replace('\n\r', '\n')
lines = s.split('\n')
else:
lines = [s]

View File

@@ -393,14 +393,13 @@ class Canvas:
def drawMultiLineString(self, s, x, y, font=None, color=None, angle=0, **kwargs):
"Breaks string into lines (on \n, \r, \n\r, or \r\n), and calls drawString on each."
import math
import string
h = self.fontHeight(font)
dy = h * math.cos(angle * math.pi / 180.0)
dx = h * math.sin(angle * math.pi / 180.0)
s = string.replace(s, '\r\n', '\n')
s = string.replace(s, '\n\r', '\n')
s = string.replace(s, '\r', '\n')
lines = string.split(s, '\n')
s = s.replace('\r\n', '\n')
s = s.replace('\n\r', '\n')
s = s.replace('\r', '\n')
lines = s.split('\n')
for line in lines:
self.drawString(line, x, y, font, color, angle)
x = x + dx

View File

@@ -4,9 +4,11 @@ This module puts the various PIDDLE backends through their paces.
"""
from __future__ import print_function
from sping import pagesizes
from sping.pid import *
import string
from rdkit.sping import pagesizes
from rdkit.sping.pid import *
from rdkit.six.moves import input
# The original code imported letters, a more generic lisit. This is no longer supported.
from string import ascii_letters as LETTERS
import math
backends = ['PDF', 'PIL', 'TK', 'PS', 'SVG', 'WX'] # 'piddleAI','piddleQD','piddleGL' ]
@@ -408,18 +410,18 @@ def mainLoop():
i = i + 1
print()
inp = raw_input("Selection (0 to exit): ")
inp = input("Selection (0 to exit): ")
print()
if inp == '0':
return
if inp:
testinp = ''
if inp[-1] in string.letters:
if inp[-1] in LETTERS:
testinp = inp[-1]
elif inp[0] in string.letters:
elif inp[0] in LETTERS:
testinp = inp[0]
backinp = string.join(filter(lambda x: x in '0123456789', inp))
backinp = ' '.join(filter(lambda x: x in '0123456789', inp))
if backinp:
backend = int(backinp) - 1
if backend < len(backends):
@@ -433,7 +435,7 @@ def mainLoop():
else:
backend = None
if testinp:
test = ord(string.upper(testinp[0])) - ord('A')
test = ord(testinp[0].upper()) - ord('A')
if test >= 0 and test < len(tests):
docstr = tests[test].__doc__
if docstr:

View File

@@ -50,6 +50,8 @@ from __future__ import print_function
import htmllib, formatter, string
from types import *
import piddle
from rdkit.six import string_types
from rdkit.six.moves import input
TRACE = 0
@@ -139,7 +141,7 @@ class _HtmlPiddleWriter:
points = self.DefaultFontSize
if fontParams[3]:
face = "courier" #"modern"
elif type(size) is StringType and size[0] == "h":
elif isinstance(size, string_types) and size[0] == "h":
face = "helvetica" #"swiss"
else:
face = "times" #"roman"
@@ -195,7 +197,7 @@ class _HtmlPiddleWriter:
self.x = self.indent
self.atbreak = 0
if TRACE:
raw_input('lb')
input('lb')
def send_hor_rule(self):
self.send_line_break()
@@ -208,11 +210,11 @@ class _HtmlPiddleWriter:
def send_literal_data(self, data):
if not data:
return
lines = string.splitfields(data, '\n')
text = string.expandtabs(lines[0])
lines = data.split(data, '\n')
text = lines[0].replace('\t', ' '*8)
for l in lines[1:]:
self.OutputLine(text, 1)
text = string.expandtabs(l)
text = l.replace('\t', ' '*8)
self.OutputLine(text, 0)
self.atbreak = 0
@@ -222,7 +224,7 @@ class _HtmlPiddleWriter:
atbreak = self.atbreak or data[0] in string.whitespace
text = ""
pixels = chars = 0
for word in string.split(data):
for word in data.split():
bword = " " + word # blank + word
length = len(bword)
# The current line is "text" and its size is
@@ -381,9 +383,9 @@ def demo(html=DEMO_HTML):
#print(' 3. piddleTK')
#print(' 4. piddleWX')
print(' 0. EXIT')
sel = raw_input('Enter Selection Number: ')
sel = input('Enter Selection Number: ')
try:
sel = string.atoi(string.strip(sel))
sel = int(sel.strip())
except Exception:
sel = -1
if (sel == 0):

View File

@@ -13,7 +13,7 @@
"""
from __future__ import print_function
import string, tempfile, os, time
import tempfile, os, time
try:
import pythoncom
from win32com.client import gencache, Dispatch, constants
@@ -385,7 +385,7 @@ def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', rest
while nextLine != '':
if nextLine.find('M END') != -1:
lines.append(nextLine)
molBlock = string.join(lines, '')
molBlock = ''.join(lines)
try:
newMolBlock = Add3DCoordsToMol(molBlock, 'chemical/mdl-molfile', props=props)
@@ -410,7 +410,7 @@ def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', rest
for prop in props.keys():
lines.append('> <%s>\n%f\n\n' % (prop, props[prop]))
lines.append(nextLine)
outFile.write(string.join(lines, ''))
outFile.write(''.join(lines))
lines = []
else:
skip = 0
@@ -418,7 +418,7 @@ def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', rest
if problemFile is None:
problemFile = open(problemFileName, 'w+')
problemFile.write(badBlock)
problemFile.write(string.join(lines, ''))
problemFile.write(''.join(lines))
lines = []
else:
lines.append(nextLine)