我正在将我之前用C#编写的应用程序转换为Python。它是一个GUI应用程序,用于在学习新语言的同时管理未知单词。当应用程序启动时,我必须从XML文件中加载具有非常简单结构的单词:
<Words>
<Word>
<Word>test</Word>
<Explanation>test</Explanation>
<Translation>test</Translation>
<Examples>test</Examples>
</Word>
</Words>
然而,我得到了:
/usr/bin/python3.5 /home/cali/PycharmProjects/Vocabulary/Vocabulary.py Traceback(最近一次调用最后一次):文件 “/home/cali/PycharmProjects/Vocabulary/Vocabulary.py”,第203行,in main()文件“/home/cali/PycharmProjects/Vocabulary/Vocabulary.py”,第198行,in 主要 gui =词汇(根)文件“/home/cali/PycharmProjects/Vocabulary/Vocabulary.py”,第28行,in 的初始化 self.load_words()文件“/home/cali/PycharmProjects/Vocabulary/Vocabulary.py”,第168行,in load_words w = Word(节点('Word')。text,node('Explanation')。text,node('Translation')。text,node('Example')。text)TypeError: 'xml.etree.ElementTree.Element'对象不可调用
这是原始的LoadWords()方法:
void LoadWords()
{
words.Clear();
listView1.Items.Clear();
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string vocabulary_path = path + "\\Vocabulary\\Words.xml";
if (!Directory.Exists(path + "\\Vocabulary"))
Directory.CreateDirectory(path + "\\Vocabulary");
if (!File.Exists(vocabulary_path))
{
XmlTextWriter xW = new XmlTextWriter(vocabulary_path, Encoding.UTF8);
xW.WriteStartElement("Words");
xW.WriteEndElement();
xW.Close();
}
XmlDocument xDoc = new XmlDocument();
xDoc.Load(vocabulary_path);
foreach (XmlNode xNode in xDoc.SelectNodes("Words/Word"))
{
Word w = new Word();
w.WordOrPhrase = xNode.SelectSingleNode("Word").InnerText;
w.Explanation = xNode.SelectSingleNode("Explanation").InnerText;
w.Translation = xNode.SelectSingleNode("Translation").InnerText;
w.Examples = xNode.SelectSingleNode("Examples").InnerText;
words.Add(w);
listView1.Items.Add(w.WordOrPhrase);
WordCount();
}
}
我不知道如何访问每个节点的内部文本。
这是我的load_words函数:
def load_words(self):
self.listBox.delete(0, END)
self.words.clear()
path = os.path.expanduser('~/Desktop')
vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml')
if not os.path.exists(vocabulary):
if not os.path.exists(os.path.dirname(vocabulary)):
os.mkdir(os.path.dirname(vocabulary))
doc = ET.Element('Words')
tree = ET.ElementTree(doc)
tree.write(vocabulary)
else:
tree = ET.ElementTree(file=vocabulary)
for node in tree.findall('Word'):
w = Word(node('Word').text, node('Explanation').text, node('Translation').text, node('Example').text)
self.words.append(w)
self.listBox.insert(w.wordorphrase)
答案 0 :(得分:1)
TypeError:&#39; xml.etree.ElementTree.Element&#39;对象不可调用
正如上面提到的错误消息,node
是Element
,而不像您在此部分中那样可以调用/调用method_name(parameters)
的方法:
w = Word(node('Word').text, node('Explanation').text, node('Translation').text, node('Example').text)
在C#中更接近SelectSingleNode()
的方法将是Element.find()
,例如,从Word
获取名为node
的第一个子元素,然后提取内部文字:
inner_text = node.find('Word').text
上下文代码中的实现如下:
w = Word(node.find('Word').text, node.find('Explanation').text, node.find('Translation').text, node.find('Example').text)