繁体   English   中英

python文件列表搜索(我有两个匹配的字符串,但是python认为它们不相等)

[英]python file list search (I have two matching strings but python doesn't think they are equal)

如果您输入的是john,为什么if语句不起作用?

studentname.txt

john 34
paul 37
poop 45

以上是studentname.txt中的内容

b=a
name = input('students name : ')
list1=[]

file=open('studentname.txt','r')
for (a) in file:
    list1.append(a)    
    b=a[:-3]    

例如,如果输入的名称为“ john”,那么如果语句跳闸,为什么下一个不是呢?

    if name == b:
        print(a)

file.close

您正在选择换行符。 根据在其上创建文件的操作系统,您将具有不同的换行符。 摆脱这种状况的最安全方法是:

a = a.rstrip()

它将处理所有尾随空白。

您也可以这样做:

for a in map(lambda x: x.rstrip(), file):

另外,不要将变量命名为“文件”。 这是python内置函数,您现在已为脚本以及导入该脚本的任何脚本重命名。

最后,您可能更喜欢处理以下文件:

with open("studentname.txt", 'r') as testfile:
    for item in (line.rstrip() for line in testfile):
        print item

无需关闭文件,with语句控制文件的范围并关闭它。

或者,您可以使用a.strip()[:-3] ,它将在获取子字符串之前修剪所有空白字符。

尝试这个:

for a in file.readlines():
    name, _, score = a.strip().partition(' ')
    if name == b:
        print(a)

它更清洁,因为它不依赖两位数的值,并且比任意索引更具表现力。 它还会删除回车符和换行符。

您面临的直接问题是,正如其他人提到的那样,您不知道数据结尾处的\\n printrepr内置功能是您的朋友; 使用它们:

if name != b:
    print repr(name), repr(b)

这样,问题的原因就显而易见了。

这是一些(未试用的)代码,它们说明了处理像您这样的简单数据文件格式时的更好做法。 它旨在应对空白/空行,未终止的最后一行以及现实生活中的可能性,例如:

Jack 9
Jill 100
Billy Bob 99
Decimus 1.23
Numberless

不会崩溃或无法正常运行。

with open('studentname.txt','rU') as f:
    for line_number, line in enumerate(f, 1):
        line = line.rstrip('\n')
        fields = line.split()
        nf = len(fields]
        if nf == 0: 
            continue: # blank/empty line
        if nf == 1:
            print('Only 1 field in line', line_number, repr(line))
            continue
        dataname = ' '.join(fields[:-1])
        try:
            datanumber = int(fields[-1])
        except ValueError:
            print('Invalid number', repr(fields[-1]), 'in line',
                line_number, repr(line))
            continue
    list1.append((dataname, datanumber))   
    if name == dataname:
        print(repr(dataname), number)

注意file.close求值为一个方法/函数对象,该对象不执行任何操作。 您需要调用它: file.close() 但是,既然您正在使用with语句,它将在关闭文件后查看,因此只需删除该file.close行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM