根据标记ID解析XML以匹配注释和文本

时间:2013-04-18 15:13:01

标签: python dictionary python-2.7 xml-parsing beautifulsoup

(更新):添加了根据其ID匹配值的代码。问题:为什么两个词典中匹配的ids u'1'和'u'0'都没有被识别?

(代码目标): 我正在编写一个脚本,它从.docx文件中获取注释文本,并通过xml标记ID将其与注释相匹配。我设法提取了评论标签,文本和ID。我现在需要匹配这些。我的策略是创建两个词典:1)一个以id为键,注释文本为值,2)第二个以id为键,注释为值。

然后我打算浏览两个词典,如果他们的键(即ids)匹配,我想制作匹配注释文本/注释对的元组。我在创建字典时遇到问题,我收到的错误消息是我创建字典的语法无效。我不太明白为什么。有什么想法吗?

from bs4 import BeautifulSoup as Soup
f = open('transcript.xml','r')
soup = Soup(f)
#print soup.prettify()

textdict = {}
for i in soup.find_all('w:commentrangestart'):

       # variable 'key' is assigned to the tag id
    key = i.parent.contents[1].attrs['w:id']

       #variable 'value' is assigned to the tag's text
    value= ''.join(i.nextSibling.findAll(text=True)

       # key / value pairs are added to the dictionary 'text_d'
    textdict[key]=value

print textdict

commentdict = {}
for i in soup.find_all('w:comment'):
    key = i.attrs['w:id']
    value= ''.join(i.findAll(text=True)
    commentdict[key]=value
print commentdict

## OUTPUT {u'1': u'contradictory about news', u'0': u'something about news'}
##        {u'1': u'News; comment; negative', u'0': u'News; comment'}

## Added Code
for key in set(textdict) & set (commentdict):
    if textdict[key] == commentdict[key]:
        print 'yay'

1 个答案:

答案 0 :(得分:1)

您遇到语法错误,因为您没有关闭括号:

value= ''.join(i.nextSibling.findAll(text=True)
                                # -------------^ missing )

你还错过了另外几行:

value= ''.join(i.findAll(text=True)
                    # -------------^ missing )