我不能让拆分字符串工作?

时间:2014-04-09 03:11:08

标签: python

我正在尝试使用二维dict来保存大量数据。我想用这个类与这个dict接口:

class font_table(object):
    def __init__(self,font_size=False):
        if(font_size!=False):
            self.size=font_size
            self.set_size=True
        else:
            self.set_size=False
    def charsize(self,letter):
        if(self.set_size):
            return reference[self.size][letter]
        else:
            return False
    def charsize2(self,size,letter):
        return reference[size][letter]
    def getstringlength(self,the_str):
        if(self.set_size):
            size = len(the_str)
            list = the_str.split()
            width=0
            height=0
            for i in range(0,size):
                the_chr = self.charsize(list[i])
                width+=the_chr[0]
                if(the_chr[1]>height):
                    height=the_chr[1]
            return (width,height)
        else:
            return False
    def getstringlength2(self,font_size,the_str):
        size = len(the_str)
        list = the_str.split()
        width=0
        height=0
        for i in range(0,size):
            the_chr = self.charsize2(font_size,list[i])
            width+=the_chr[0]
            if(the_chr[1]>height):
                height=the_chr[1]
        return (width,height)

用作:

from fonttable import font_table

my_table = font_table(16)
size = my_table.charsize("g")
print "char size of g: %r" % size[0]
size = my_table.getstringlength("sweet pie of mine")
print "size of string: \"sweet pie of mine\": %r" % size[0]

错误:

char size of g: 4
Traceback (most recent call last):
  File "test-font-table.py", line 6, in <module>
    size = my_table.getstringlength("sweet pie of mine")
  File "/Users/me/Desktop/whatever/src/fonttable.py", line 1164, in getstringlength
    the_chr = self.charsize(list[i])
  File "/Users/me/Desktop/whatever/src/fonttable.py", line 1152, in charsize
    return reference[self.size][letter]
KeyError: 'sweet'

1 个答案:

答案 0 :(得分:1)

getstringlength函数中存在一些问题。这是一个快速解决方法:

def getstringlength(self,the_str):
    if(self.set_size):
        size = len(the_str)
        width, height = 0, 0
        for the_chr in the_str:
            the_chr_dims = self.charsize(the_chr)
            width += the_chr_dims[0]
            if(the_chr_dims[1] > height):
                height = the_chr_dims[1]
        return (width,height)
    else:
        return False

略微清理版本:

def getstringlength(self,the_str):
    if not self.set_size: return False
    dims = map(self.charsize, the_str)
    width = sum(d[0] for d in dims)
    height = max(d[1] for d in dims)
    return (width, height)