python:在文本文件中搜索列表中的值

时间:2013-06-30 12:57:46

标签: python string list csv

我试图在大型文本文件中搜索单词列表。而不是为每个单词反复运行命令,我认为列表会更容易,但我不知道如何去做。下面的脚本或多或少使用字符串值,但我想用'dict'列表的每个值替换下面的'字符串'。

import csv

count = 0
dic = open('dictionary','r') #changed from "dict" in original post
reader = csv.reader(dic)
allRows = [row for row in reader]
with open('bigfile.log','r') in inF:
   for line in inF:
      if 'string' in line: #<---replace the 'string' with dict values
         count += 1
count

1 个答案:

答案 0 :(得分:2)

将您的文件转换为设置:

 with open('dictionary','r') as d:
     sites = set(l.strip() for l in d)

现在,您可以为每行进行有效的成员资格测试,如果您可以拆分行

with open('bigfile.log','r') as inF:
   for line in inF:
       elements = line.split()
       if sites.intersection(elements):
           count += 1