2013-06-30 54 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。 –