2011-12-15 82 views
0

我不得不採取從包含座標來繪製字符列於TurtleWorld一個文本文件中的值,該文本文件的一個例子如下:閱讀和編輯字體文件和使用字典

<character=B, width=21, code=66> 
4 21 
4 0 
-1 -1 
4 21 
13 21 
16 20 
17 19 
18 17 
18 15 
17 13 
16 12 
13 11 
-1 -1 
4 11 
13 11 
16 10 
17 9 
18 7 
18 4 
17 2 
16 1 
13 0 
4 0 
</character> 

然後我必須編寫一個函數來獲取所有這些點,然後將它們轉換成字典,其中一個鍵是字符,相應的值是可用於在TurtleWorld中繪製該字符的點集。

我已經試過代碼如下:

def read_font(): 
    """ 
    Read the text from font.txt and convert the lines into instructions for how to plot specific characters 
    """ 

    filename = raw_input("\n\nInsert a file path to read the text of that file (or press any letter to use the default font.txt): ") 
    if len(filename) == 1: 
     filename = 'E:\words.txt' 
     words = open(filename, 'r') 
    else: 
     words = open(filename, 'r') 

    while True:                     # Restarts the function if the file path is invalid 
     line = words.readline() 
     line = line.strip() 
     if line[0] == '#' or line[0] == ' ':             # Used to omit the any unwanted lines of text 
      continue 
     elif line[0] == '<' and line[1] == '/':             # Conditional used for the end of each character 
      font_dictionary[character] = numbers_list 
     elif line[0] == '<' and line[1] != '/':        
+1

你有非常多的代碼那裏不是讀書的分塊更時髦 文件... – 2011-12-15 03:40:54

回答

0

看看http://oreilly.com/catalog/pythonxml/chapter/ch01.html ::具體而言,打了題爲例如::例1-1:bookhandler.py

可以或多或少的信用/複製,並調整它來閱讀你特定的XML。一旦你的「勇氣」(你coords)使用,你真的可以很容易地將其分割成X/Y COORDS列表

a = "1 3\n23 4\n3 9\n" 
coords = map(int,a.split()) 

和大塊它到一個列表W/2組How do you split a list into evenly sized chunks? 並將結果字母[信] =導致

,或者你可以做使用re模塊

import re 
a = "1 13\n4 5\n" 
b = re.findall("\d+ *\d+",a) 
c = [map(int,item.split()) for item in b] 
c 
[[1, 13], [4, 5]]