为什么我需要一个“elif”声明在这里? [英] Why do I require an "elif" statement here?

查看:90
本文介绍了为什么我需要一个“elif”声明在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么我需要elif char ==''\ n''"在

下面的代码?

这是必需的,以便只有空格的拾取行。

为什么不

" else:"声明选择了吗?


OLD_INDENT = 5#空格

NEW_INDENT = 4#空格


打印'' Reindent.py:''

print''\ nFrom file%s''%infile

print''将%i空格缩进更改为%i space indentation。' '%(

OLD_INDENT,NEW_INDENT)

print''并将修改后的文件放入%s''%outfile


空格=''''

n = 0

nline = 0
对于input.readlines()中的行


nline + = 1

#只查看以空格开头的行。

如果行[0] ==空格:

i = 0

for char in line:

i + = 1

if char == whitespace:

传递

elif char ==''\ n'':#为什么我需要这个只用空格的

空行?

output.write(line)

break

else:#为什么不是空白线路

在这里被拿起来?

x = line.count(空白* OLD_INDENT,0,i)

#Reindent行完全具有多个

OLD_INDENT。

如果x 0和(i-1)%OLD_INDENT == 0:

output.write(空格* NEW_INDENT * x + line.lstrip())

n + = 1

break

else:

output.write (线)

休息

其他:

output.write(行)


输入。 close()

output.close()

print''%i行重新排出%i行的总数。''%(n,

nline)

解决方案

有人可以告诉我为什么我需要elif char ==''\ n '' "在


以下代码?


这是必需的,以便只有空格的取货行

in。

为什么不是否则:声明接这个?



按照以下代码进行操作:


如果该行仅包含换行符,则会因

if line [0] == whitespace"线。但是,如果行

只包含空格后跟换行符,则* * * *
成功转到其他行有问题。没有其他

的地方供你去。


然而,接下来会发生什么?如果你落入你的上半部分

你的if x 0 ...声明:


你从你的

lstrip()调用中删除所有** * true *空格。由于你的whitespace

(简单空格)与\ n之间没有任何内容,所以\ n被lstrip()

调用吞没。因此,你输出.write()一个空字符串。


我建议一些明智的放置print repr(thing)作为

的行,你试着调试,看看事情是不是你期望的那样

是。


As另一个侧灯,而不是使用i = 0,i + = 1。方面,

你可以使用更多的pythonic成语


for i,char in enumerate(line):


(考虑到我变为零基础)。这将自动更新i
。每个通行证。


-tkc


>

OLD_INDENT = 5#spaces

NEW_INDENT = 4#空格


打印''Reindent.py:''

打印''\ nFrom文件%s ''%infile

print''将%i空格缩进更改为%i空格缩进。''%(

OLD_INDENT,NEW_INDENT)

print''并将修改后的文件放入%s''%outfile


whitespace =''''

n = 0

nline = 0


for input.readlines():

nline + = 1

#只查看那些行从一个空格开始。

如果行[0] ==空格:

i = 0

for char in line:

i + = 1

if char == whitespace:

pass

elif char ==''\ n'':#为什么我需要这个只有空格的

空行吗?

output.write(行)

break

:否则:#为什么不是空行

在这里被拿起来?

x = line.count(空白* OLD_INDENT,0,i)

#Reindent行具有正好的倍数

OLD_INDENT。

如果x 0和(i-1)%OLD_INDENT == 0:

output.write(空格* NEW_INDENT * x + line.lstrip())

n + = 1

break

else:

output.write(line)

break

else:

output.write(line)


input.close()

output.close()

print''%i行重新排出%i行的总数。''%(n,

nline)


Jim,你写的内容应该正常工作。我很好奇为什么你这样做是为了b / b
。一种更简单的方法是取出所有

这个字符处理并使用内置字符串处理。请参阅

此代码:


-------------------------- -----

whitespace ="

old_indent = 3

new_indent = 5


x ="从3个空格开始


x = x.replace(空白* old_indent,空白* new_indent)

------------ -------------------


在这个例子中,无论在哪里都会取代3个空格

他们在,而不仅仅是在开始......但是,对于大多数用例来说,它可能更实际。

Jim写道:


有人可以告诉我为什么我需要elif char ==''\ n''"在

下面的代码?

这是必需的,以便只有空格的拾取行。

为什么不

" else:"声明选择了吗?


OLD_INDENT = 5#空格

NEW_INDENT = 4#空格


打印'' Reindent.py:''

print''\ nFrom file%s''%infile

print''将%i空格缩进更改为%i space indentation。' '%(

OLD_INDENT,NEW_INDENT)

print''并将修改后的文件放入%s''%outfile


空格=''''

n = 0

nline = 0
对于input.readlines()中的行


nline + = 1

#只查看以空格开头的行。

如果行[0] ==空格:

i = 0

for char in line:

i + = 1

if char == whitespace:

通过

elif char ==''\ n'':#为什么我需要这个只用空格的

空行?

output.write(行)

休息

else:#为什么不是空行

在这里拿到了吗?

x = line.count(空白* OLD_INDENT,0,i)

#Reindent行具有
$ b $的倍数b OLD_INDENT。

如果x 0和(i-1)%OLD_INDENT == 0:

output.write(空白* NEW_INDENT * x + line.lstrip())

n + = 1

休息

否则:

output.write(line)

break

else:

output.write(line)


input.close()

output.close()

print''%i行重新排出%i行的总数。''%(n,

nline)


Jim写道:

有人可以告诉我为什么我需要elif char ==''\ n''"在

下面的代码?

这是必需的,以便只有空格的拾取行。

为什么不

" else:"声明接这个?



不知道。看看你的程序的配置文件:for .. if .. for .. if ..

else .. if ..这不好。你之所以遇到麻烦,是因为你没有以一种简单易用的方式编写它来调试和测试。如果一个代码块最终在屏幕中间缩进

,这意味着你做错了什么。


这个程序应该分成少数几个小功能

各做一件事。以下是稍微长一点,但非常简单。
更简单。最重要的是,它可以从python shell导入

,每个函数都可以单独测试。


def leading_spaces(line):

"""返回前导空格的数量""

num = 0

for char in line:

如果char!='''':

休息

num + = 1

返回数字


def change_indent(line,old,new):

"""使用old:new""
的比率更改此行的缩进
ws = leading_spaces(行)


#如果没有领先的空白,

#或者它不是旧缩进的倍数,什么都不做

如果ws == 0或ws%old:

返回行


#otherwise更改缩进

new_spaces = ws / old * new

new_indent =''''* new_spaces

返回new_indent + line.lstrip('''')

def reindent(ifname,ofname,old,新):

f = open(ifname)

o = open(ofname,''w'')


for line in f:

line = change_indent(line,old,new)

o.write(line)


f.close( )

o.close()


if __name__ ==" __ main __":

试试:

ifname,ofname,old,new = sys.argv [1:]

old = int(old)

new = int(new)

除了ValueError:

print" blah"

sys.exit(1)


reindent(ifname, ofname,old,new)


Could somebody tell me why I need the "elif char == ''\n''" in the
following code?
This is required in order the pick up lines with just spaces in them.
Why doesn''t
the "else:" statement pick this up?

OLD_INDENT = 5 # spaces
NEW_INDENT = 4 # spaces

print ''Reindent.py:''
print ''\nFrom file %s'' % infile
print ''Change %i space indentation to %i space indentation.'' % (
OLD_INDENT, NEW_INDENT)
print ''And place revised file into %s'' % outfile

whitespace = '' ''
n = 0
nline = 0

for line in input.readlines():
nline += 1
# Only look at lines that start with a space.
if line[0] == whitespace:
i = 0
for char in line:
i += 1
if char == whitespace:
pass
elif char == ''\n'': # Why do I need this for a
blank line with only spaces?
output.write(line)
break
else: # Why doesn''t the blank line
get picked up here?
x = line.count(whitespace*OLD_INDENT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x 0 and (i-1)%OLD_INDENT == 0:
output.write(whitespace*NEW_INDENT*x+line.lstrip() )
n += 1
break
else:
output.write(line)
break
else:
output.write(line)

input.close()
output.close()
print ''Total number of %i lines reindented out of %i lines.'' % (n,
nline)

解决方案

Could somebody tell me why I need the "elif char == ''\n''" in

the following code?

This is required in order the pick up lines with just spaces
in them.
Why doesn''t the "else:" statement pick this up?

Following through with the below code:

if the line consists of only a newline, it gets ignored due to
the "if line[0] == whitespace" line. However, if the line
consists of only whitespace followed by a newline you *do*
successfully get to the "else" in question. There''s no other
place for you to go.

However, what happens then? If you fall into you the top half of
your "if x 0 ..." statement:

you strip **all** *true* whitespace from the line with your
lstrip() call. Since there''s nothing between your "whitespace"
(simple spaces) and the \n, the \n gets swallowed by the lstrip()
call. Thus, you output.write() an empty string.

I recommend a few judiciously placed "print repr(thing)" lines as
you try to debug to see where things aren''t what you expect them
to be.

As another sidelight, rather than using the "i=0, i+= 1" aspect,
you can use the more pythonic idiom of

for i, char in enumerate(line):

(taking into consideration that i becomes zero-based). This will
automatically update "i" on each pass.

-tkc

>
OLD_INDENT = 5 # spaces
NEW_INDENT = 4 # spaces

print ''Reindent.py:''
print ''\nFrom file %s'' % infile
print ''Change %i space indentation to %i space indentation.'' % (
OLD_INDENT, NEW_INDENT)
print ''And place revised file into %s'' % outfile

whitespace = '' ''
n = 0
nline = 0

for line in input.readlines():
nline += 1
# Only look at lines that start with a space.
if line[0] == whitespace:
i = 0
for char in line:
i += 1
if char == whitespace:
pass
elif char == ''\n'': # Why do I need this for a
blank line with only spaces?
output.write(line)
break
else: # Why doesn''t the blank line
get picked up here?
x = line.count(whitespace*OLD_INDENT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x 0 and (i-1)%OLD_INDENT == 0:
output.write(whitespace*NEW_INDENT*x+line.lstrip() )
n += 1
break
else:
output.write(line)
break
else:
output.write(line)

input.close()
output.close()
print ''Total number of %i lines reindented out of %i lines.'' % (n,
nline)


Jim, what you wrote should work correctly. I''m curious as to why you
are doing it this way though. An easier way would be to take out all
this character processing and use the builtin string processing. See
this code:

-------------------------------
whitespace = " "
old_indent = 3
new_indent = 5

x = " starts with 3 spaces"

x = x.replace(whitespace*old_indent, whitespace*new_indent)
-------------------------------

In this example though, it will replace the 3 spaces no matter where
they are at, not just in the beginning... still, it''s probably more
practical for most use cases.
Jim wrote:

Could somebody tell me why I need the "elif char == ''\n''" in the
following code?
This is required in order the pick up lines with just spaces in them.
Why doesn''t
the "else:" statement pick this up?

OLD_INDENT = 5 # spaces
NEW_INDENT = 4 # spaces

print ''Reindent.py:''
print ''\nFrom file %s'' % infile
print ''Change %i space indentation to %i space indentation.'' % (
OLD_INDENT, NEW_INDENT)
print ''And place revised file into %s'' % outfile

whitespace = '' ''
n = 0
nline = 0

for line in input.readlines():
nline += 1
# Only look at lines that start with a space.
if line[0] == whitespace:
i = 0
for char in line:
i += 1
if char == whitespace:
pass
elif char == ''\n'': # Why do I need this for a
blank line with only spaces?
output.write(line)
break
else: # Why doesn''t the blank line
get picked up here?
x = line.count(whitespace*OLD_INDENT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x 0 and (i-1)%OLD_INDENT == 0:
output.write(whitespace*NEW_INDENT*x+line.lstrip() )
n += 1
break
else:
output.write(line)
break
else:
output.write(line)

input.close()
output.close()
print ''Total number of %i lines reindented out of %i lines.'' % (n,
nline)


Jim wrote:

Could somebody tell me why I need the "elif char == ''\n''" in the
following code?
This is required in order the pick up lines with just spaces in them.
Why doesn''t
the "else:" statement pick this up?

No idea. Look at the profile of your program: for.. if.. for.. if..
else.. if.. This is NOT good. The reason why you are having trouble
getting it to work is that you are not writing it in a way that is easy
to debug and test. If one block of code ends up being indented halfway
across the screen it means you are doing something wrong.

This program should be split up into a handful of small functions that
each do one thing. The following is slightly longer, but immensely
simpler. Most importantly, it can be imported from the python shell
and each function can be tested individually.

def leading_spaces(line):
"""Return the number of leading spaces"""
num = 0
for char in line:
if char != '' '':
break
num += 1
return num

def change_indent(line, old, new):
"""Change the indent of this line using a ratio of old:new"""
ws = leading_spaces(line)

#if there was no leading whitespace,
#or it wasn''t a multiple of the old indent, do nothing
if ws == 0 or ws % old:
return line

#otherwise change the indent
new_spaces = ws/old*new
new_indent = '' '' * new_spaces
return new_indent + line.lstrip('' '')
def reindent(ifname, ofname, old, new):
f = open(ifname)
o = open(ofname, ''w'')

for line in f:
line = change_indent(line, old, new)
o.write(line)

f.close()
o.close()

if __name__ == "__main__":
try :
ifname, ofname, old, new = sys.argv[1:]
old = int(old)
new = int(new)
except ValueError:
print "blah"
sys.exit(1)

reindent(ifname, ofname, old, new)


这篇关于为什么我需要一个“elif”声明在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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