elif 给出语法错误python? [英] elif giving syntax error python?

查看:57
本文介绍了elif 给出语法错误python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 XML 文档并获取某些标签.我想获取名称标签(仅当它是嵌套在艺术家中的名称标签时)和标题标签(仅当它是嵌套在发布中的标签时).
不过,这并不太重要,重要的是我出于某种原因收到一个错误,说 elif 语句是无效语法
我查看了其他帖子并确保我的 Tab 键是正确的,并且在任何 if 之后没有任何额外的换行符.

I'm trying to parse an XML document and get certain tags. I'd like to grab the name tag (only if it's the name tag nested within artist) and the title tag (only if it's the one nested within release).
That's not too important, though, the important thing is that I'm for some reason getting an error saying the elif statement is invalid syntax
I've looked through other posts and made sure that my tabbing is correct and that there aren't any extra newlines after any of the if's.

这是代码片段:

from lxml import etree
import sys

#infile = raw_input("Please enter an XML file to parse:  ")
outfile = open('results.txt', 'a')

path = []
for event, elem in etree.iterparse('releases7.xml', events=("start", "end")):
    if event == 'start':
        path.append(elem.tag)
    elif event == 'end':
        # process the tag
        if elem.tag == 'name':
            if 'artist' in path and not 'extraartists' in path and not 'track' in path:
                outfile.write( 'artist = ' + elem.text.encode('utf-8') + '\n' )
        elif elem.tag == 'title':
            if 'release' in path and not 'track' in path:
                outfile.write( 'release title = ' + elem.text.encode('utf-8') + '\n')
            else:
                print 'nonrelease'
        path.pop()

这是错误:

File "DataDestroy_Fast.py", line 18
elif elem.tag == 'title':
   ^
SyntaxError: invalid syntax

(注意:在 Mac OSX 上使用 Python2.7)

(Note: Using Python2.7 on Mac OSX)

推荐答案

正如我在评论中提到的,我曾经遇到过这样的错误,这是由于一个额外的制表符恰好正好位于它所在的位置没有什么可见的.

As I mentioned in a comment, I had an error like this once that was due to a extra tab character that just happened to be right at a position where it did nothing visible.

如果您的编辑器允许您查看不可见的字符,例如制表符和换行符,您或许能够真正了解情况是否如此.我的编辑器还可以选择将制表符转换为空格来解决此类问题.如果一切都失败了,只需删除该行开头的所有空格,然后小心地重新执行,然后查看是否仍然出现错误.

If your editor will let you view invisible characters like tabs and newlines, you may be able to actually see if that the case. My editor also has an option to convert tabs to spaces which would fix such a problem. If all else fails, just delete all the whitespace at the beginning of the line and then carefully do it over and then see if the error still occurs.

最近我遇到了一个非常好的回答类似的问题如何向此代码添加打印语句不会出现缩进错误.

Recently I ran across a really good answer to a similar question How can I add a print statement to this code without getting an indentation error.

这篇关于elif 给出语法错误python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆