读取和编辑字体文件及使用字典
我需要从一个文本文件中获取一些值,这些值是用来在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 个回答
0
你可以看看这个链接:http://oreilly.com/catalog/pythonxml/chapter/ch01.html,特别是里面有个例子叫做:Example 1-1: bookhandler.py。
你可以大致参考或复制那个例子,然后稍微修改一下,来读取你自己的XML文件。一旦你拿到了里面的“核心内容”(比如坐标),你就可以很简单地把它分成一个包含x和y坐标的列表。
比如说:
a = "1 3\n23 4\n3 9\n"
coords = map(int,a.split())
然后把它分成每组2个的列表,具体可以参考这个链接:如何把一个列表分成均匀大小的块?,最后把结果存储为letters[letter] = result。
或者你也可以用更有趣的方法,通过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]]