~ubuntu-branches/ubuntu/hardy/gnue-common/hardy

« back to all changes in this revision

Viewing changes to src/utils/TextUtils.py

  • Committer: Bazaar Package Importer
  • Author(s): Andrew Mitchell
  • Date: 2005-03-09 11:06:31 UTC
  • Revision ID: james.westby@ubuntu.com-20050309110631-8gvvn39q7tjz1kj6
Tags: upstream-0.5.14
ImportĀ upstreamĀ versionĀ 0.5.14

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#
 
2
# This file is part of GNU Enterprise.
 
3
#
 
4
# GNU Enterprise is free software; you can redistribute it
 
5
# and/or modify it under the terms of the GNU General Public
 
6
# License as published by the Free Software Foundation; either
 
7
# version 2, or (at your option) any later version.
 
8
#
 
9
# GNU Enterprise is distributed in the hope that it will be
 
10
# useful, but WITHOUT ANY WARRANTY; without even the implied
 
11
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 
12
# PURPOSE. See the GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public
 
15
# License along with program; see the file COPYING. If not,
 
16
# write to the Free Software Foundation, Inc., 59 Temple Place
 
17
# - Suite 330, Boston, MA 02111-1307, USA.
 
18
#
 
19
# Copyright 2001-2005 Free Software Foundation
 
20
#
 
21
# FILE:
 
22
# TextUtils.py
 
23
#
 
24
# DESCRIPTION:
 
25
# Common text-related utilities
 
26
#
 
27
# NOTES:
 
28
#
 
29
 
 
30
import string
 
31
 
 
32
ALIGN_LEFT=0
 
33
ALIGN_RIGHT=1
 
34
ALIGN_CENTER=2
 
35
 
 
36
# very simple lineWrap
 
37
def lineWrap(message,maxWidth, preserveNewlines=1, alignment=ALIGN_LEFT, eol=1):
 
38
  """
 
39
  A simple linewrap function.
 
40
 
 
41
  @param message:   The string to wrap
 
42
  @param maxWidth:  The maximum string width allowed.
 
43
  @param preserveNewlines: If true then newlines are left in the string
 
44
                           otherwise they are removed.
 
45
  @param alignment: The alignment of the returned string based upon
 
46
                    a width of maxWidth.
 
47
 
 
48
                    Possible values (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER)
 
49
 
 
50
  @param eol: If true then the last character of the return value
 
51
              will be a newline
 
52
 
 
53
  @return: The properly wrapped text string.
 
54
  @rtype: string
 
55
  """
 
56
 
 
57
  text = ""
 
58
 
 
59
  temptext = string.strip(str(message))
 
60
  if preserveNewlines:
 
61
    buff = string.split(temptext,"\n")
 
62
  else:
 
63
    buff = (temptext,)
 
64
 
 
65
  for strings in buff:
 
66
    while len(strings) > maxWidth:
 
67
      index = 0
 
68
 
 
69
      for sep in [' ',',',':','.',';']:
 
70
        ind = string.rfind(strings,sep,0,maxWidth-1)+1
 
71
        if ind > index: index = ind
 
72
 
 
73
      if index > maxWidth or index==0:
 
74
        index = maxWidth-1
 
75
 
 
76
      line = strings[:index]
 
77
      if alignment == ALIGN_CENTER:
 
78
        line = ' ' * ( (maxWidth - len(line)) /2 ) + line
 
79
      elif alignment == ALIGN_RIGHT:
 
80
        line = ' ' * ( (maxWidth - len(line)) ) + line
 
81
      text += "%s\n" % line
 
82
      strings = strings[index:]
 
83
 
 
84
    line = strings
 
85
    if alignment == ALIGN_CENTER:
 
86
      line = ' ' * ( (maxWidth - len(line)) /2 ) + line
 
87
    elif alignment == ALIGN_RIGHT:
 
88
      line = ' ' * ( (maxWidth - len(line)) ) + line
 
89
    text += "%s\n" % line
 
90
 
 
91
  if not eol:
 
92
    return text[:-1]
 
93
  else:
 
94
    return text
 
95
 
 
96
 
 
97
def textToMeasurement(text, multiplier=1):
 
98
  """
 
99
  Converts most standard measurements to inches.
 
100
 
 
101
  Sample Usage:
 
102
 
 
103
  >>> textToMeasurement('72pt')
 
104
  1.0
 
105
  >>> # convert to 72 point output
 
106
  ... textToMeasurement('1.27cm',72)
 
107
  36.0
 
108
 
 
109
  @param text: A string containing the measurement to convert
 
110
               The following measurements are accepted
 
111
               (pt, cm, mm, in)
 
112
  @type text: string
 
113
  @param multiplier: A multiplier used to adjust the output
 
114
                     to values other inches.
 
115
  @type multipler: number
 
116
 
 
117
  @return: The converted value
 
118
  @rtype: number
 
119
  """
 
120
  if text[-1] in ('0','1','2','3','4','5','6','7','8','9'):
 
121
    value = float(text) / 72 * multiplier
 
122
  else:
 
123
    unit = text[-2:]
 
124
    text = text[:-2]
 
125
    value = float(text) / {'pt':72, 'in':1, 'cm':2.54,
 
126
                           'mm': 25.4}[unit.lower()] * multiplier
 
127
 
 
128
  return value
 
129
 
 
130
 
 
131
def intToRoman(num):
 
132
  """
 
133
  Convert an integer to a roman numeral.
 
134
 
 
135
  Sample Usage:
 
136
 
 
137
  >>> intToRoman(1999)
 
138
  'MCMXCIX'
 
139
 
 
140
  @param num: The number to convert
 
141
  @type num: integer
 
142
 
 
143
  @return: The roman numeral equivalent.
 
144
  @rtype: string
 
145
  """
 
146
  n = int(num) # just in case
 
147
  rv = ""
 
148
  for dec, rom in (
 
149
      (1000, 'M'), (900, 'CM', ),
 
150
      (500, 'D'), (400, 'CD'), (100, 'C'),
 
151
      (90, 'XC'),(50, 'L'), (40, 'XL'),
 
152
      (10, 'X'), (9, 'IX'), (5, 'V'),
 
153
      (4, 'IV'), (1, 'I') ):
 
154
    while (n >= dec):
 
155
      n -= dec;
 
156
      rv += rom;
 
157
  return rv
 
158
 
 
159
 
 
160
def dollarToText(num):
 
161
  """
 
162
  Convert a number to "dollar" notation (suitable for use on checks)
 
163
  e.g., 123.24 --> "One Hundred Twenty Three and 24/100"
 
164
 
 
165
  Sample Usage:
 
166
 
 
167
  >>> dollarToText(1120.15)
 
168
  'One Thousand One Hundred Twenty and 15/100'
 
169
 
 
170
  @param num: The numeric amount
 
171
  @type num: number
 
172
 
 
173
  @return: The full text equivalent of the number.
 
174
  @rtype: string
 
175
  """
 
176
  whole = int(num)
 
177
  cents = round((num-whole)*100)
 
178
  rv = 'and %02d/100' % cents
 
179
  if whole:
 
180
    thirdRange = 0
 
181
    while whole:
 
182
      whole, segment = divmod(whole, 1000)
 
183
      hundreds, tens = divmod(segment, 100)
 
184
      try:
 
185
        rv = _smallDollarMap[tens] + _thirdDollarMap[thirdRange] + rv
 
186
      except IndexError:
 
187
        ten, ones = divmod(tens,10)
 
188
        rv = _tenDollarMap[ten] + _smallDollarMap[ones] + _thirdDollarMap[thirdRange] + rv
 
189
      if hundreds:
 
190
        rv = _smallDollarMap[hundreds] + 'Hundred ' + rv
 
191
      thirdRange += 1
 
192
  else:
 
193
    rv = 'Zero ' + rv
 
194
 
 
195
  return rv
 
196
 
 
197
 
 
198
_smallDollarMap = ('', 'One ', 'Two ', 'Three ', 'Four ', 'Five ',
 
199
                   'Six ', 'Seven ', 'Eight ', 'Nine ', 'Ten ',
 
200
                   'Eleven ', 'Twelve ', 'Thirteen ', 'Fourteen ',
 
201
                   'Fifteen ', 'Sixteen ', 'Seventeen ', 'Eighteen ',
 
202
                   'Nineteen ' )
 
203
_tenDollarMap = ('', '', 'Twenty ', 'Thirty ', 'Forty ', 'Fifty ',
 
204
                 'Sixty ', 'Seventy ', 'Eighty ', 'Ninety ')
 
205
_thirdDollarMap = ('', 'Thousand ', 'Million ', 'Billion ', 'Trillion ')
 
206
 
 
207
 
 
208
 
 
209
# Comify a number
 
210
def comify(num, decimals=2, parenthesis=0):
 
211
  """
 
212
  Comify a number (e.g., print -9900 as -9,900.00)
 
213
 
 
214
  Sample Usage:
 
215
 
 
216
  >>> comify(-9999.934, 2)
 
217
  '-9,999.93'
 
218
  >>> comify(-9999.934, 2, 1)
 
219
  '(9,999.93)'
 
220
 
 
221
  @param num: The number to reformat
 
222
  @type num: number
 
223
  @param decimals: The number of decimal places to retain
 
224
  @type decimals: number
 
225
  @param parenthesis: If true then negative numbers will be returned inside parenthesis
 
226
  @type  parenthesis: number
 
227
 
 
228
  @return: A properly formatted number
 
229
  @rtype: string
 
230
  """
 
231
  neg = num < 0
 
232
  num = abs(num)
 
233
  whole, dec = (string.split(string.strip(("%%12.%sf" % decimals) % abs(num)),'.') + [""])[:2]
 
234
  if len(dec):
 
235
    dec = "." + dec
 
236
 
 
237
  s = ""
 
238
 
 
239
  for i in range(divmod(len(whole),3)[0]+1):
 
240
    j = len(whole) - i*3
 
241
    s = "," + whole[j > 3 and j-3 or 0:j] + s
 
242
 
 
243
  s += dec
 
244
 
 
245
  while s[:1] == ',':
 
246
    s = s[1:]
 
247
 
 
248
  if neg:
 
249
    if parenthesis:
 
250
      s = "(%s)" % s
 
251
    else:
 
252
      s = "-" + s
 
253
  elif parenthesis:
 
254
    s += " "
 
255
 
 
256
  return s