|
Revision 1, 1.4 kB
(checked in by davea, 3 years ago)
|
---
|
| Line | |
|---|
| 1 |
import re |
|---|
| 2 |
import email.Utils |
|---|
| 3 |
|
|---|
| 4 |
def wrap(text, width): |
|---|
| 5 |
""" |
|---|
| 6 |
A word-wrap function that preserves existing line breaks |
|---|
| 7 |
and most spaces in the text. Expects that existing line |
|---|
| 8 |
breaks are posix newlines (\n). |
|---|
| 9 |
From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 |
|---|
| 10 |
""" |
|---|
| 11 |
return reduce(lambda line, word, width=width: '%s%s%s' % |
|---|
| 12 |
(line, |
|---|
| 13 |
' \n'[(len(line)-line.rfind('\n')-1 |
|---|
| 14 |
+ len(word.split('\n',1)[0] |
|---|
| 15 |
) >= width)], |
|---|
| 16 |
word), |
|---|
| 17 |
text.split(' ') |
|---|
| 18 |
) |
|---|
| 19 |
|
|---|
| 20 |
def get_from_addr(addr): |
|---|
| 21 |
""" |
|---|
| 22 |
Parses the From: header |
|---|
| 23 |
Returns the name, email address, or the string it was given (in that order) |
|---|
| 24 |
""" |
|---|
| 25 |
parsedfrom = email.Utils.parseaddr(addr) |
|---|
| 26 |
if parsedfrom[0] != '': |
|---|
| 27 |
return parsedfrom[0] |
|---|
| 28 |
elif parsedfrom[1] != '': |
|---|
| 29 |
return parsedfrom[1] |
|---|
| 30 |
else: |
|---|
| 31 |
return addr |
|---|
| 32 |
|
|---|
| 33 |
def findlinks(s): |
|---|
| 34 |
""" |
|---|
| 35 |
returns a list of all http:// or https:// links |
|---|
| 36 |
in the input string |
|---|
| 37 |
""" |
|---|
| 38 |
p = re.compile(".*(http[s]?\S+)", re.M) |
|---|
| 39 |
links = [] |
|---|
| 40 |
for line in s.splitlines(): |
|---|
| 41 |
m = p.match(line) |
|---|
| 42 |
try: |
|---|
| 43 |
for l in m.groups(): |
|---|
| 44 |
links.append(l) |
|---|
| 45 |
except: |
|---|
| 46 |
pass |
|---|
| 47 |
return links |
|---|
| 48 |
|
|---|
| 49 |
def makelinks(s): |
|---|
| 50 |
""" |
|---|
| 51 |
Converts plain text http[s]:// addresses to <a href=""></a> equivalents |
|---|
| 52 |
""" |
|---|
| 53 |
for link in findlinks(s): |
|---|
| 54 |
s = s.replace(link, "<a href=\"%s\">%s</a>" % (link, link)) |
|---|
| 55 |
return s |
|---|