Roughly approximate text line width in Python?

How does one, using Python, approximate the font width of a given line of text?

I am looking for a function with a prototype similar to:

def getApproximateFontWidth(the_string, font_name="Arial", font_size=12):
   return ... picas or pixels or something similar ...

I'm not looking for anything very strict, the approximation will be fine.

The motivation for this is that I generate a truncated string in my webapp firewall and send it to the external interface for display. In most cases, the strings are lowercase, but sometimes the strings are in all caps, which makes them very wide. If the line is not executed correctly, it looks ugly. I would like to know how to crop lines based on their approximate width. If it is 10%, it is not very important, it is a cosmetic function.

+5
source share
3 answers

, 80% , . Arial, 12 pt, , , .

def getApproximateArialStringWidth(st):
    size = 0 # in milinches
    for s in st:
        if s in 'lij|\' ': size += 37
        elif s in '![]fI.,:;/\\t': size += 50
        elif s in '`-(){}r"': size += 60
        elif s in '*^zcsJkvxy': size += 85
        elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
        elif s in 'BSPEAKVXY&UwNRCHD': size += 112
        elif s in 'QGOMm%W@': size += 135
        else: size += 50
    return size * 6 / 1000.0 # Convert to picas

, :

def truncateToApproximateArialWidth(st, width):
    size = 0 # 1000 = 1 inch
    width = width * 1000 / 6 # Convert from picas to miliinches
    for i, s in enumerate(st):
        if s in 'lij|\' ': size += 37
        elif s in '![]fI.,:;/\\t': size += 50
        elif s in '`-(){}r"': size += 60
        elif s in '*^zcsJkvxy': size += 85
        elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
        elif s in 'BSPEAKVXY&UwNRCHD': size += 112
        elif s in 'QGOMm%W@': size += 135
        else: size += 50
        if size >= width:
            return st[:i+1]
    return st

:

>> width = 15
>> print truncateToApproxArialWidth("the quick brown fox jumps over the lazy dog", width) 
the quick brown fox jumps over the
>> print truncateToApproxArialWidth("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG", width) 
THE QUICK BROWN FOX JUMPS

:

FOX JUMPS

+5

I used a library that does this, but it requires pygame: http://inside.catlin.edu/site/compsci/ics/python/graphics.py Look under sizeString

+1
source

All Articles