将精确的单词与txt文件进行比较

时间:2015-08-09 22:27:16

标签: python python-3.x

我正在尝试从我的文件中获取与他们的行号相同的单词匹配。 就像当我搜索abc10时,它给了我所有可能的答案,例如abc102 abc103等 我怎么能限制我的代码只打印我命令...

这是我的代码!

lineNo = 0

linesFound = []

inFile= open('rxmop.txt', 'r')

sKeyword = input("enter word ")
done = False

while not done :

    pos = inFile.tell()
    sLine = inFile.readline()
    if sLine == "" :
        done = True
        break

    if (sLine.find( sKeyword ) != -1):
        print ("Found at line: "+str(lineNo))
        tTuple = lineNo, pos
        linesFound.append( tTuple )
    lineNo = lineNo + 1
done = False
while not done :

    command = int( input("Enter the line you want to view: ") )

    if command == -1 :
        done = True
        break
    for tT in linesFound :
        if command == tT[0] :
            inFile.seek( tT[1] )
            lLine = inFile.readline()
            print ("The line at position " + str(tT[1]) + "is: " + lLine) 

1 个答案:

答案 0 :(得分:0)

“就像当我搜索abc10时,它给了我所有可能的答案,例如abc102 abc103等”

您拆分每条记录并仅比较整个“单词”。

to_find = "RXOTG-10"
list_of_possibles = ["RXOTG-10 QTA5777 HYB SY G12",
                     "RXOTG-100 QTA9278 HYB SY G12"]
for rec in list_of_possibles:
    words_list=rec.strip().split()
    if to_find in words_list:
        print "found", rec
    else:
        print "     NOT found", rec