2016-06-07 105 views
1

我試圖在我的文本文件中打印包含我列表中任何單詞的所有行,並且顯示「名稱」。我遇到的問題是我的程序迭代太多,重複的行會因爲多次迭代而打印出來。我怎樣才能打印線路發生一次?另外我怎樣才能將行打印到輸出文件?在一行中找到一個子字符串並在python中打印該行並僅打印一行?

這是我到目前爲止有:

names=[bob,carter,jim,mike] 
with open("base.txt") as openfile: 
     for line in openfile: 
      for part in line.split(): 
       for i in names: 
        if i in part: 

         print line 

回答

0

無需分割線,只需檢查線作爲一個整體包含名稱。另外,不需要檢查每個名字,第一場比賽就會完成。 any將幫助你避免一些坎坷代碼:

with open("base.txt") as openfile: 
    for line in openfile: 
     if any(name in line for name in names): 
      print line 
+0

我認爲如果塊缺少':'。 OP也詢問如何寫入文件。如果你添加它,你的答案將會完成。 – SilentMonk

+0

@SilentMonk Thx請注意。更新! – schwobaseggl

0

檢查一次所有的名字,並使用any()如下。

names=['bob','carter','jim','mike'] 
with open("base.txt") as openfile: 
    for line in openfile: 
     if any([n in line for n in names]): 
      print line.strip() 

[n in line for n in names]所做的是檢查行中的每個名稱並返回一個布爾值列表。 any()檢查列表中的任何元素是否爲True

0

您可以使用正則表達式匹配字符串:

import re 

names=["bob","carter","jim","mike"] 
match_string = "(" + ")|(".join(names)+")" #create a regex that can match all the words in the list names 
outfile = open("out.txt","w") #open output file 


with open("base.txt") as openfile: 
     for line in openfile: 
       if re.search(match_string,line): 
         outfile.write(line) #writes output to the file 
         print line 

outfile.close() 
0

正如其他已經發布,你可以使用any確認在該行的名稱中至少一個的發生。使用列表理解把所有匹配的行成一個列表:

with open("base.txt") as openfile, open("output.txt", "w") as outputfile: 
    result = [line if any(n in line for n in names) for line in openfile] 
    outputfile.writelines(result) # wwii's comment: the lines already contain a separator 

要寫入resultoutputfile,你應該使用writelines方法,採取result序列參數(@二戰的評論)。

+0

如果原始文件中存在行分隔符,結果中的每一行不應該結束於行分隔符中嗎?如果是這樣的話'''outputfile.writelines(result)''' – wwii

+0

我的不好。我在想什麼。謝謝 –