我必须从包含坐标的文本文件中取值来在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中绘制该字符的点集。 / p>
我尝试过的代码如下:
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] != '/':
答案 0 :(得分: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个How do you split a list into evenly sized chunks?组的列表 并存储结果字母[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]]