2013-06-30 56 views
2

即时尝试搜索大型文本文件中的单词列表。而不是一遍又一遍地为每个单词运行一个命令,我认为列表会更容易,但我不知道如何去做。下面的脚本或多或少地处理字符串值,但我想用“字典”列表的每个值替换下面的“字符串”。python:在列表中搜索文本文件中的值

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 
+3

不要命名一个变量'dict';它掩盖了内置。你可以做'list(reader)'而不是list comp。 –

+0

'dictionary' CSV文件包含多少列?什么是列值?你想匹配什么专栏。 –

+0

我有一列数千行。该列表是已知垃圾邮件网站的黑名单。列表看起来像你期望的,spam.spam.com或其他。在csv文件中没有','只是'\ n' – 16num

回答

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 
+0

耶!感谢Martijn Pieters和其他人。 – 16num

+0

@sixteenornumber:感谢您的纠正;对于代码更改,将其作为评论通常会更容易,因为像这样的次代码错字更正往往不被拒绝,因为评论者不能期望知道python。 –