【发布时间】: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 文件。