简体   繁体   English

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

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

if your input is john why isn't the if statement kicking in???? 如果您输入的是john,为什么if语句不起作用?

studentname.txt

john 34
paul 37
poop 45

above is whats in studentname.txt 以上是studentname.txt中的内容

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

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

why isn't this next if statement tripping if name entered is 'john' for instance?? 例如,如果输入的名称为“ john”,那么如果语句跳闸,为什么下一个不是呢?

    if name == b:
        print(a)

file.close

You are picking up newlines. 您正在选择换行符。 Depending on the os you created the file on, you'll have different new line characters. 根据在其上创建文件的操作系统,您将具有不同的换行符。 The safest way to rid yourself of this is: 摆脱这种状况的最安全方法是:

a = a.rstrip()

That will take care of any trailing whitespace. 它将处理所有尾随空白。

You could also do: 您也可以这样做:

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

Also, don't name your variable 'file'. 另外,不要将变量命名为“文件”。 This is a python built-in function that you've now renamed for your script and any script that imports it. 这是python内置函数,您现在已为脚本以及导入该脚本的任何脚本重命名。

Finally, you might prefer to handle files like this: 最后,您可能更喜欢处理以下文件:

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

No need to close the file, the with statement controls it's scope and closes it. 无需关闭文件,with语句控制文件的范围并关闭它。

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

Try this: 尝试这个:

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

It is cleaner in that it doesn't rely on a 2-digit value and is more expressive than arbitrary indexes. 它更清洁,因为它不依赖两位数的值,并且比任意索引更具表现力。 It also strips carriage returns and newlines. 它还会删除回车符和换行符。

Your immediate problem is as others have mentioned that you are not aware of the \\n at the end of your data. 您面临的直接问题是,正如其他人提到的那样,您不知道数据结尾处的\\n print and the repr built-in function are your friends; printrepr内置功能是您的朋友; use them: 使用它们:

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

whereupon the cause of the problem becomes obvious. 这样,问题的原因就显而易见了。

Here is some (untested) code that illustrates better practice when handling simple data file formats like yours. 这是一些(未试用的)代码,它们说明了处理像您这样的简单数据文件格式时的更好做法。 It is intended to cope with blank/empty lines, unterminated last line, and real-life possibilities like: 它旨在应对空白/空行,未终止的最后一行以及现实生活中的可能性,例如:

Jack 9
Jill 100
Billy Bob 99
Decimus 1.23
Numberless

without crashing or running amok. 不会崩溃或无法正常运行。

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)

Note file.close evaluates to a method/function object, which does nothing. 注意file.close求值为一个方法/函数对象,该对象不执行任何操作。 You need to call it: file.close() . 您需要调用它: file.close() However now that you are using the with statement, it will look after closing the file, so just delete that file.close line. 但是,既然您正在使用with语句,它将在关闭文件后查看,因此只需删除该file.close行。

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

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