在Python中将Doc对象转换为字符串
我正在使用minidom来解析一个xml文档。我提取了带有yum标签的数据,并把它们存储在一个列表中,然后计算了这些词的出现频率。不过,列表里并没有把它们当作字符串来存储或读取。有没有其他方法可以做到这一点?现在我有的代码是:
yumNodes = [node for node in doc.getElementsByTagName("yum")]
for node in yumNodes:
yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)
for ob in yumlist:
for o in ob:
if word not in freqDict:
freqDict[word] = 1
else:
freqDict[word] += 1
2 个回答
0
把
yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)
替换成下面这个:
yumlist.append(t.nodeValue for t in node.childNodes if t.nodeType == 3)
1
这和你的问题不完全相关,但我想说一些可以让你的代码更好的建议……这个写法
freqDict = {}
...
if word not in freqDict:
freqDict[word] = 1
else:
freqDict[word] += 1
通常可以用下面的方式替代
import collections
freqDict = collections.defaultdict(int)
...
freqDict[word] += 1
或者在2.5之前的版本
freqDict = {}
...
freqDict.setdefault(word, 0) += 1