<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 (most recent call last): File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 203, in main() File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 198, in main gui = Vocabulary(root) File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 28, in init self.load_words() File "/home/cali/PycharmProjects/Vocabulary/Vocabulary.py", line 168, in load_words w = Word(node('Word').text, node('Explanation').text, node('Translation').text, node('Example').text) TypeError: 'xml.etree.ElementTree.Element' object is not callable
这是原始的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)
w = Word(node.find('Word').text,node.find('Explanation').text,node.find('Translation').text,node.find('Example').text)
,但出现了“AttributeError:'NoneType' object has no attribute 'text'”的错误提示。 - user7822402find(...)
没有找到参数中提到的子元素,因此返回None
,并且None
没有text
属性,正如错误信息所述。 - har07