。开始不起作用

发布于 2024-10-28 21:30:03 字数 2740 浏览 1 评论 0原文

在我的程序中,我有一个文件,然后我通读 for 循环中的所有行,检查每一行的开头内容。然后将每一行添加为变量。其中有 40 多行,它们几乎都是相同的,但其中一个 elif 语句没有返回 true,.startswith 不起作用。无论如何,这里是文件内容,基本上是一堆保存的信息 fN 将是我保存的变量,而 john 将是我想要的。所以这个方法就是这样做的,或者它应该是

fN:john
fP:1
fE:father email
mN:mother name
mP:1
mE:mother email @ bomg.com
a:1233 adress lane
c:city
s:state
zC:1234534
hP:(1928)phone-1123
cP:1113333
eN:emergancy
eNu:number
c1N:cluubiie 1
c1G:1st
c1B:1-23-34
c2N:clubbie 2
c2G:grade 2
c2B:birth 2
c3N:clubb 3 
c3G:grade 3
c3B:birth 3

方法

def fillWindow(self,student):
    global fileDirectory
    location = os.path.join(fileDirectory, student + '.txt')
    file = open(location, 'r')

    for line in file.xreadlines():
        if line.startswith('fN'):
            fN = line.split(':')[1]
        elif line.startswith('fP'):
            fP = line.split(':')[1]
        elif line.startswith('fE'):
            fE = line.split(':')[1]
        elif line.startswith('mN'):
            mN = line.split(':')[1]
        elif line.startswith('mP'):
            mP = line.split(':')[1]
        elif line.startswith('mE'):
            mE = line.split(':')[1]
        elif line.startswith('a'):
            a = line.split(':')[1]
        elif line.startswith('c'):
            c = line.split(':')[1] 
        elif line.startswith('s'):
            s = line.split(':')[1]
        elif line.startswith('zC'):
            zC = line.split(':')[1]
        elif line.startswith('hP'):
            hP = line.split(':')[1]

这里永远不会返回 True,即使文件中有一行以 cP 开头

        elif line.startswith('cP'):
            cP = line.split(':')[1]
            print('True') 
        elif line.startswith('eN'):
            eN = line.split(':')[1]
        elif line.startswith('eNu'):
            eNu = line.split(':')[1]
        elif line.startswith('c1N'):
            c1N = line.split(':')[1] 
        elif line.startswith('c1G'):
            c1G = line.split(':')[1]
        elif line.startswith('c1B'):
            c1B = line.split(':')[1] 
        elif line.startswith('c2N'):
            c2N = line.split(':')[1] 
        elif line.startswith('c2G'):
            c2G = line.split(':')[1]
        elif line.startswith('c2B'):
            c2B = line.split(':')[1]
        elif line.startswith('c3N'):
            c3N = line.split(':')[1] 
        elif line.startswith('c3G'):
            c3G = line.split(':')[1]
        elif line.startswith('c3B'):
            c3B = line.split(':')[1]
        elif line.startswith('c4N'):
            c4N = line.split(':')[1] 
        elif line.startswith('c4G'):
            c4G = line.split(':')[1]
        elif line.startswith('c4B'):
            c4B = line.split(':')[1]

In My program I have a file and then I read through all the lines in a for loop checking each line for what it begins with. Then adding each line as a variable. There are a little over 40 lines in this and they are all pretty much the same but one of the elif statements doesnt return true the .startswith isnt working. anyways here is the file contents basically a bunch of saved information fN would be the variable I saved and john would be what I want it to be. So this method does just that or it is suppose to

fN:john
fP:1
fE:father email
mN:mother name
mP:1
mE:mother email @ bomg.com
a:1233 adress lane
c:city
s:state
zC:1234534
hP:(1928)phone-1123
cP:1113333
eN:emergancy
eNu:number
c1N:cluubiie 1
c1G:1st
c1B:1-23-34
c2N:clubbie 2
c2G:grade 2
c2B:birth 2
c3N:clubb 3 
c3G:grade 3
c3B:birth 3

Method

def fillWindow(self,student):
    global fileDirectory
    location = os.path.join(fileDirectory, student + '.txt')
    file = open(location, 'r')

    for line in file.xreadlines():
        if line.startswith('fN'):
            fN = line.split(':')[1]
        elif line.startswith('fP'):
            fP = line.split(':')[1]
        elif line.startswith('fE'):
            fE = line.split(':')[1]
        elif line.startswith('mN'):
            mN = line.split(':')[1]
        elif line.startswith('mP'):
            mP = line.split(':')[1]
        elif line.startswith('mE'):
            mE = line.split(':')[1]
        elif line.startswith('a'):
            a = line.split(':')[1]
        elif line.startswith('c'):
            c = line.split(':')[1] 
        elif line.startswith('s'):
            s = line.split(':')[1]
        elif line.startswith('zC'):
            zC = line.split(':')[1]
        elif line.startswith('hP'):
            hP = line.split(':')[1]

right here True is never returned even though in the file there is a line that starts with cP

        elif line.startswith('cP'):
            cP = line.split(':')[1]
            print('True') 
        elif line.startswith('eN'):
            eN = line.split(':')[1]
        elif line.startswith('eNu'):
            eNu = line.split(':')[1]
        elif line.startswith('c1N'):
            c1N = line.split(':')[1] 
        elif line.startswith('c1G'):
            c1G = line.split(':')[1]
        elif line.startswith('c1B'):
            c1B = line.split(':')[1] 
        elif line.startswith('c2N'):
            c2N = line.split(':')[1] 
        elif line.startswith('c2G'):
            c2G = line.split(':')[1]
        elif line.startswith('c2B'):
            c2B = line.split(':')[1]
        elif line.startswith('c3N'):
            c3N = line.split(':')[1] 
        elif line.startswith('c3G'):
            c3G = line.split(':')[1]
        elif line.startswith('c3B'):
            c3B = line.split(':')[1]
        elif line.startswith('c4N'):
            c4N = line.split(':')[1] 
        elif line.startswith('c4G'):
            c4G = line.split(':')[1]
        elif line.startswith('c4B'):
            c4B = line.split(':')[1]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

那小子欠揍 2024-11-04 21:30:03

您应该考虑这两行如何交互:

elif line.startswith('c'):
...
elif line.startswith('cP'):

此外,您应该考虑使用字典来保存所有值,这样可以大大缩短程序。

You should think about how these two lines interact:

elif line.startswith('c'):
...
elif line.startswith('cP'):

Also, you should look into using a dictionary to hold all your values, you could drastically shorten your program.

九公里浅绿 2024-11-04 21:30:03

这是一段非常可怕的代码。您真的需要所有这些元素都是单独的变量吗?为什么不按照这些思路编写字典:

{'fN':'john',
 'fP':'1',
   ...
}

您只需几行即可生成它:

dct = {}
f = file(location, 'r')
for line in f:
    k, v = line.split(':')
    dct[k] = v

That's a pretty horrible chunk of code. Do you really need all those elements to be individual variables? Why not a dictionary along these lines:

{'fN':'john',
 'fP':'1',
   ...
}

which you could generate in a couple of lines only:

dct = {}
f = file(location, 'r')
for line in f:
    k, v = line.split(':')
    dct[k] = v
故人的歌 2024-11-04 21:30:03

由于您对除第一个之外的所有替代方案都使用 elif,因此最多会评估其中一个替代方案。对于以 cP 开头的行,该条件

elif line.startswith('c'):

也成立,因此不会考虑其他替代方案。

也就是说,您最好将结果存储在字典中,也许像这样:

d = dict(line.split(":", 1) for line in open(location))

Since you are using elif for all alternatives but the first one, at most one of the alternatives ever gets evaluated. For a line starting with cP, the condition

elif line.startswith('c'):

will also hold, so none of the further alternatives will be considered.

That said, you might be better off storing your result in a dictionary, maybe like this:

d = dict(line.split(":", 1) for line in open(location))
深居我梦 2024-11-04 21:30:03

它不起作用,因为以 cP 开头的行也以 c 开头,并且您将 c 条件放在 cP 之前>。


您应该更好地重构代码以避免长 if/elif 链。这是非常难以维护的。我会使用字典,

 results = {}
 for line in file:
    (key, value) = line.split(':', 1)
    results[key] = value

 # use results['fN'] for your fN variable

甚至更短:(

 results = dict(line.split(':', 1) for line in file)

如果你必须使用 fN 作为独立的局部变量,你可以使用,

 locals().update(line.split(':', 1) for line in file)

但我不推荐它。)

It does not work because a line starts with cP also starts with c, and you placed the c condition before cP.


You should better refactor your code to avoid the long if/elif chain. It is very unmaintainable. I would use a dictionary and

 results = {}
 for line in file:
    (key, value) = line.split(':', 1)
    results[key] = value

 # use results['fN'] for your fN variable

or even shorter:

 results = dict(line.split(':', 1) for line in file)

(If you must use fN as an independent local variable, you could use

 locals().update(line.split(':', 1) for line in file)

but I don't recommend it.)

岁吢 2024-11-04 21:30:03

由于名称 fN 、 fP 、 fE 、 mN 、 mP ……显然是已知且稳定的,并且由于函数定义中的 self 背叛了您想要创建实例的属性文件中读取的值,并且由于该文件具有 CSV 格式,因此我的建议是:

import csv

class A:
def __init__(self):
    self.fN  = self.fP  = self.fE  = None 
    self.mN  = self.mP  = self.mE  = None
    self.a   = self.c   = self.s   = None
    self.zC  = self.hP  = self.cP  = None
    self.eN  = self.c1N = self.c1G = None
    self.c1B = self.c2N = self.c2G = None
    self.c2B = self.c3N = self.c3G = None
    self.c3B = None

inst1 = A()

with open('roro.txt','rb') as f:
    rid = csv.reader(f,delimiter=':')
    for row in rid:
        inst1.__dict__[row[0]] = row[1]


print inst1.fP
print inst1.s
print inst1.c3B

请注意,使用内置函数的名称命名对象(即 file)是这是一个不好的做法,并且 xreadlines() 已被弃用。

此外,定义 global fileDirectory 的目的是什么?

语句 global x 指定,如果通过在下一行中对名称 x 进行赋值来完成对象的创建,则名称为 x< 的对象/strong> 必须被视为处于全局级别的模块中。在您的代码中,没有对 fileDirectory 进行赋值,这样会更好,因为将 fileDirectory 声明为全局可能会引发意想不到的错误。

请注意,全局级别是较高级别,而不是函数的外部级别。检查以下代码:

class A:

    def __init__(self):
        self.m = 0.00315879

    N = 101

    def f(self,x,y):
        print 'in f : x==',x,"  y+10==",y
        def g(a,b):
            print 'in g : a==',a,'  b==',b
            global m
            global N
            m = a*b
            N = 5000010000
            print 'in g : m = a*b ==',m
            print 'in g : N==',N


        g(x+300,y+700)
        print 'in f, outside g: m==',m
        print 'in f, outside g: N==',N



u = A()


u.f(0,40)
print
print 'm at the global level==',m
print 'N at the global level==',N
print 'the instance attribute u.m==',u.m
print 'the class attribute u.N==',u.N

结果

in f : x== 0   y+10== 40
in g : a== 300   b== 740
in g : m = a*b == 222000
in g : N== 5000010000
in f, outside g: m== 222000
in f, outside g: N== 5000010000

m at the global level== 222000
N at the global level== 5000010000
the instance attribute u.m== 0.00315879
the class attribute u.N== 101

Since the names fN , fP , fE , mN, mP, .... are manifestly known and steady, and since the self in your definition of the function betrays you want to create attributes of an instance with values read in the file, and since the file has a CSV format, my proposition is to do:

import csv

class A:
def __init__(self):
    self.fN  = self.fP  = self.fE  = None 
    self.mN  = self.mP  = self.mE  = None
    self.a   = self.c   = self.s   = None
    self.zC  = self.hP  = self.cP  = None
    self.eN  = self.c1N = self.c1G = None
    self.c1B = self.c2N = self.c2G = None
    self.c2B = self.c3N = self.c3G = None
    self.c3B = None

inst1 = A()

with open('roro.txt','rb') as f:
    rid = csv.reader(f,delimiter=':')
    for row in rid:
        inst1.__dict__[row[0]] = row[1]


print inst1.fP
print inst1.s
print inst1.c3B

Note that naming an object with the name of a built-in function ( that is to say file) is a bad practice, and that xreadlines() is deprecated.

.

Moreover, what is your intention by defining global fileDirectory ?

The statement global x specifies that if the creation of an object is done thanks to an assignement done to name x in the next lines, the object of name x must be considered as being in the module of global level. In your code there is no assignement to fileDirectory and it's better because declaring fileDirectory as global could provoke unsuspected errors.

Note that the global level is the higher level , not the outside level of a function. Examine the following code:

class A:

    def __init__(self):
        self.m = 0.00315879

    N = 101

    def f(self,x,y):
        print 'in f : x==',x,"  y+10==",y
        def g(a,b):
            print 'in g : a==',a,'  b==',b
            global m
            global N
            m = a*b
            N = 5000010000
            print 'in g : m = a*b ==',m
            print 'in g : N==',N


        g(x+300,y+700)
        print 'in f, outside g: m==',m
        print 'in f, outside g: N==',N



u = A()


u.f(0,40)
print
print 'm at the global level==',m
print 'N at the global level==',N
print 'the instance attribute u.m==',u.m
print 'the class attribute u.N==',u.N

result

in f : x== 0   y+10== 40
in g : a== 300   b== 740
in g : m = a*b == 222000
in g : N== 5000010000
in f, outside g: m== 222000
in f, outside g: N== 5000010000

m at the global level== 222000
N at the global level== 5000010000
the instance attribute u.m== 0.00315879
the class attribute u.N== 101
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文