我想基于另一个文件中的关键字列表来提取XML文件的某些节点;如果关键字存在于指示节点中,则该节点的文本以及其他某些节点的文本应写入CVS文件中。 有人可以告诉我为什么我的代码不起作用吗?尽管我确信关键字在指示节点中存在,但是只有头部写入了输出文件!
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring
import csv
tree=ET.parse('/Users/m/dru.xml')
tree = tree.getroot()
t = tostring(tree)
t = t.lower()
tree= ET.fromstring(t)
dru = open('/Us/druall.csv', 'a')
csvwriter = csv.writer(dru)
dru_head = []
count = 0
keywords=open('/Users/m/test.txt', 'r')
for channel in tree.findall('.//drug'):
if count == 0:
Indication_header = channel.find('./indication').tag
dru_head.append(Indication_header)
Name_header = channel.find('name').tag
dru_head.append(Name_header)
[x.encode('utf-8') for x in dru_head]
csvwriter.writerow(dru_head)
count = count + 1
if channel.find('./indication') is not None:
comment = channel.find('./indication')
if comment.text is not None:
for x in keywords:
x.strip().strip("").lower()
dru_info = []
if x in comment.text:
dru_info.append(channel.find('indication').text)
if channel.find('name') is not None:
dru_info.append(channel.find('name').text)
else:
print("Name: No data")
else:
print(" ");
csvwriter.writerow(dru_info)
drugB.close()
感谢您的帮助!