繁体   English   中英

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

[英](Python) Searching for a exact string in .txt and returning result

我正在尝试编写一个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()

任何解决我的问题的帮助都将不胜感激。 :)

谢谢,安德鲁

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

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

暂无
暂无

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

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