在python中将Doc对象转换为字符串

2024-06-28 19:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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

Tags: in文档标记node列表forifxml
2条回答

与你的问题没有直接关系,但作为一个可以改进你的代码的注释…模式

freqDict = {}
...
if word not in freqDict:
    freqDict[word] = 1
else:
    freqDict[word] += 1

通常被替换为

^{pr2}$

或2.5之前的版本

freqDict = {}
...
freqDict.setdefault(word, 0) += 1

更换

yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)

包括以下内容:

^{pr2}$

相关问题 更多 >