2015-12-13 60 views
-1

我遇到了我的代碼問題。我想在逗號分隔的文本文件中搜索一個字符串。python 3 - 搜索文本文件 -

文件中的每一行都是一個包含8個字段的記錄,用逗號分隔。在這個練習中,我喜歡只搜索第一個字段。

的 「myfile.txt的」 看起來是這樣的:

joe,smith,111 jorge st,autin,texas,usa,00005 
john,bush,Avenue George V,paris,Halifax,canada,00006 
denise,Hoche,Avenue George V,paris,Greater Paris,france,00007 

我只能夠找到一號線文:

搜索文本:喬 [ '喬', 「鐵匠」,「111豪爾赫聖」,「autin」,「得克薩斯」,「美國」,「00005 \ n」]

如果我搜索了在第2行文字,它不返回結果

搜索文本:丹尼斯 找不到文本

while True: 
search = input ('search for text: ') 
with open('myfile.txt', 'r') as f: 
    for line in f: 
     if search in line: 
      text1, test2, text3, text4, text4, text5, text6,text7 = line.split(',') 
      print (text1) 
      break 
     print ('cannot find the text') 
     break 

請讓我知道什麼是錯的。謝謝

+1

你看過你的代碼嗎? –

+0

當你想讓代碼打印「can find」信息?從你的代碼或消息文本的psuedo-english中看不出你真正想要它做什麼。 – Blckknght

+0

我改爲「找不到文字」。謝謝你指出拼寫錯誤 –

回答

-1

檢查它是否可以幫助你。

file=open(file="hello.txt",encoding='utf-8',mode='r') 
    counter=1 
    #Put your search key here use input() 
    search="joe" 
    def mole(search,collector,counter): 
     #This will search for keyword from collector which is a list type 
     for elem in collector: 
      if search==elem: 
       print("Matched") 
       print("Line no :",counter) 
       break 
      else: 
       pass 

    for lines in file: 
     if lines=='\n': 
      print("EOF..") 
      break 
      collector=lines.split(",") 
      #To strip "\n" from lines in file 
      collector[6]=collector[6].strip('\n') 
      mole(search,collector,counter) 
      counter+=1 
    file.flush() 
    file.close() 
    print("Search complete..") 


hello.txt---- 

joe,smith,111 jorge st,autin,texas,usa,05 
jhhfghg,smith,111 jorge st,autin,texas,usa,02 
jhhfghg,smith,111 jorge st,autin,texas,usa,03 
jhhfghg,smith,111 jorge st,autin,texas,usa,00006fdg 
jhhfghg,smith,111 jorge st,autin,texas,usa,00006fgdf 
jhhfghg,smith,111 jorge st,autin,texas,usa,0000fdg6 
jhhfghg,smith,111 jorge st,autin,texas,usa,0000fgf 
+0

我的問題與我的代碼有關。 我正在搜索整個文件,但只有返回結果如果記錄存在於第1行。 –

+0

一個解釋可以走的距離 – davejal

+0

@beginningpython我沒有看你的代碼,並對我的一些更改,所以它工作正常! – mahindra