(Python)在.txt中搜索精确的字符串并返回结果

时间:2015-04-04 00:18:14

标签: python string search logging text

我试图编写一个Python程序,提示用户输入一个字符串,然后打开一个文本文件,在文件中搜索完全匹配,然后返回与该字符串相关的详细信息。

返回的字符串存储到变量中,然后写入单独的新.txt文件。 (我基本上创建了一个记录我所有火腿无线电联系人的日志文件。)

我遇到的问题是它返回字符串中的所有内容而不是完全匹配。 (例如,如果用户输入K8YP,它将返回K8YPA,K8YPB,K8YPC等,而不仅仅是K8YP)。

以下是文本文件结构的示例:

EN|215000|||AA0A|L|L00209566|MC CARTHY, DENNIS J|DENNIS|J|MC CARTHY|||||5022 LANSDOWNE AVE|SAINT LOUIS|MO|63109|||000|0002274249|I|||^M
EN|215001|||AA0AA|L|L00196154|MONKS, WILLIAM S|WILLIAM|S|MONKS|||||W 529 Nebraska Hall, UN-L|Lincoln|NE|685880514||c/o Scott L. Gardner, HWML|000|0002268431|I|||^M
EN|215002|||AA0AB|L|L00185374|CROM SR, RAYMOND L|RAYMOND|L|CROM|SR||||12291 BRIGHTON RD|HENDERSON|CO|80640|33||000|0002144756|I|||^M
EN|215003|||AA0AC|L||PETH, ESTHER T|ESTHER|T|PETH|||||BENEDICTINE CONVENT|CLYDE|MO|64432|||000||I|||^M
EN|215004|||AA0AD|L|L00310459|Odermann, William|William||Odermann|||||804 Second Street NW|New Prague|MN|56071|||000|0004694238|I|||^M

我目前的代码列在下面......

#This program will log amateur radio contacts and store them in a database.

import time
import sys

def main():
    countdown =3
    print ("\n")
    print "Starting in"

    for countdown in range (3, 0, -1):
        print countdown
        time.sleep(0.25)
    print ("\n")    
    #Asking user for callsign input data
    callsign = raw_input('Please enter the callsign: ')
    print ("\n")

    #Asking user for frequency input data
    frequency = raw_input('Please enter the frequency in MHz: ')
    print ("\n")

    #Asking user to review and confirm the entry
    print ('Callsign: ' + callsign)
    print('Frequency: ' + frequency)
    print ("\n")

    request = raw_input('Enter 1 to confirm and 0 to cancel: ')
    print ("\n")

    #Commands for grabbing date and time
    date_time_stamp = time.strftime("%c")

    if request == '1':
        with open('EN.dat', 'r') as searchfile:
            for line in searchfile:
                if callsign in line:
                    text_file = open("Contact_Logs.txt", "a")
                    text_file.write("Callsign: %s\n" % callsign)
                    text_file.write("Frequency: %s\n" % frequency)
                    text_file.write("Date/Time: %s\n" % date_time_stamp)
                    text_file.write("%s\n" % line)
                    text_file.close
                    print line
                    print("The contact was logged successfully!")
                    print ("\n")

    else:
        print "Log request was cancelled!"
        print ("\n")

    return 0

if __name__ == '__main__':
    main()

非常感谢任何帮助解决我的问题。 :)

谢谢, 安德鲁

1 个答案:

答案 0 :(得分:0)

根据提供的示例,您应该搜索"|"+callsign+"|"以避免误报:if ("|"+callsign+"|") in line:。这假设" |"之间没有空格。和呼号等。

基于正则表达式的方法会更加健壮,但还需要做更多的工作。