Python:将RTF文件转换为unicode?

时间:2010-02-03 13:49:43

标签: python unicode

我正在尝试将RTF文件中的行转换为一系列unicode字符串,然后在行上进行正则表达式匹配。 (我需要它们是unicode,以便我可以将它们输出到另一个文件。)

然而,我的正则表达式匹配不起作用 - 我认为因为它们没有被正确转换为unicode。

这是我的代码:

usefulLines = []
textData = {}

# the regex pattern for an entry in the db (e.g. SUF 76,22): it's sufficient for us to match on three upper-case characters plus a space
entryPattern = '^([A-Z]{3})[\s].*$'  

f = open('textbase_1a.rtf', 'Ur')
fileLines = f.readlines()

# get the matching line numbers, and store in usefulLines
for i, line in enumerate(fileLines):
    #line = line.decode('utf-16be') # this causes an error: I don't really know what file encoding the RTF file is in...
    line = line.decode('mac_roman')
    print line
    if re.match(entryPattern, line):
        # now retrieve the following lines, all the way up until we get a blank line
        print "match: " + str(i)
        usefulLines.append(i)

目前,这会打印所有线条,但不会打印任何匹配的内容 - 尽管它应该匹配。此外,出于某种原因,线条在开始时以'/ par'打印。当我尝试将它们打印到输出文件时,它们看起来很奇怪。

部分问题是我不知道要指定的编码。我怎么能找到这个?

如果我使用entryPattern = '^.*$',我会得到匹配。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

你甚至没有解码RTF文件。 RTF 只是简单的文本文件。例如,包含“äöü”的文件包含:

  

{\ rtf1 \ ansi \ ansicpg1252 \ deff0 \ deflang1031 {\ fonttbl {\ f0 \ fswiss \ fcharset0 Arial;}}

     

{* \ generator Msftedit 5.41.15.1507;} \ viewkind4 \ uc1 \ pard \ f0 \ fs20 \'e4 \'f6 \'fc \ par

     

}

在文本编辑器中打开时。所以字符“äöü”编码为文件开头声明的windows-1252(äöü= 0xE4 0xF6 0xFC)。

对于阅读RTF,您首先需要将RTF转换为文本的内容(已经asked here)。