python - 解析和排序 Python 字典中的键

标签 python dictionary xml-parsing beautifulsoup

我创建了以下字典:

code dictionary =  {u'News; comment; negative': u'contradictory about news', u'News; comment': u'something about news'}

我现在想编写一些 Python 代码来遍历字典的键并分离出代码及其对应的值。所以对于字典中的第一个元素,我想以:

News: 'contradictory about news', 'something about news'
comment: 'contradictory about news', 'something about news'
negative: 'contradictory about news'

最终结果可以是字典、列表、制表符或逗号分隔的文本。

你可以在这里看到我的尝试:

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


#searches text for all w:commentrangestart tags and makes a dictionary that matches ids with text
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']
        key = str(key)
        #variable 'value' is assigned to the tag's text
        value= ''.join(i.nextSibling.findAll(text=True))
        # key / value pairs are added to the dictionary 'textdict'
        textdict[key]=value
print "Transcript Text = " , textdict

# makes a dictionary that matches ids with codes        
codedict = {}
for i in soup.find_all('w:comment'):
        key = i.attrs['w:id']
        key = str(key)
        value= ''.join(i.findAll(text=True))
        codedict[key]=value
print "Codes = ", codedict

# makes a dictionary that matches all codes with text
output = {}
for key in set(textdict.keys()).union(codedict.keys()):
        print "key= ", key
        txt = textdict[key]
        print "txt = ", txt
        ct = codedict[key]
        print "ct= ", ct
        output[ct] = txt
        #print "output = ", output
print "All code dictionary = ", output

#codelist={}
#for key in output:
#   codelist =key.split(";")
#print "codelist= " , codelist


code_negative = {}
code_news = {}
print output.keys()
for i in output:
    if 'negative' in output.keys():
        print 'yay'
        code_negative[i]=textdict[i]
        print 'text coded negative: ' , code_negative
    if 'News' in i:
        code_news[i]=textdict[i]
        print 'text coded News: ' ,code_news

虽然出于某种原因,当我运行最后一个函数时,我不断收到一个关键错误:

code_negative = {}
code_news = {}
for i in output:
    if 'negative' in output.keys():
        code_negative[i]=textdict[i]
    print 'text coded negative: ' , code_negative
if 'News' in i:
    code_news[i]=textdict[i]
    print 'text coded News: ' ,code_news

有什么想法吗?谢谢!

最佳答案

如果我正确理解了问题,下面的代码应该可以工作:

from collections import defaultdict

out = defaultdict(list)
for k, v in code_dictionary.viewitems():
    for item in k.split('; '):
        out[item].append(v)

关于python - 解析和排序 Python 字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121387/

相关文章:

python - 使用数据框将列数据显示为单独的列

python - 如何将 dict.get() 的默认参数用于复杂数据

Python 字典打印所有键的所有值

Python3 : create selective copy of dictionary as a new dictionary

python - 需要帮助将子元素中的文本替换为 XML 中多个子元素中的文本

python - Numpy,为什么 `x += y` 产生的结果与 `x = x + y` 不同?

python setuptools setup.cfg : Including main- and subpackages in the build dir

android - 使用 dom 解析进行嵌套 xml 解析

java - JAXB:部分解码返回空域对象

python - EOL 字符串文字使用 webdriver selenium 创建保存位置