【问题标题】:Python: convert RTF file to unicode?Python:将 RTF 文件转换为 unicode?
【发布时间】:2010-02-03 13:49:42
【问题描述】:

我正在尝试将 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 = '^.*$',那么我会得到匹配。

谁能帮忙?

【问题讨论】:

  • 不要使用正则表达式来解析 rtf 文件。

标签: python unicode


【解决方案1】:

您甚至没有解码 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)。

【讨论】:

  • 好吧,我不知道。谢谢。
猜你喜欢
  • 1970-01-01
  • 2010-11-06
  • 2010-12-23
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多