2016-06-07 89 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

我的不好。我在想什么。谢谢 –