2013-06-26 49 views
0

我有一个单词数据库和一个带有文本行的数据集。每次在单词文件中出现的文本文件行中都有一个单词时,我想要执行一个操作。我的代码如下所示:if ... in - 不匹配时它必须是

import re 
f = open(r"words.txt") 
print len(flist) 
d = open(r"text.txt", "r") 
dlist = d.readlines() 

for line in flist: 
    lowline = line.lower() 
    for word in dlist: 
     lowword = word.lower() 
     if lowword in lowline: 
      *trick* 

然而,这段代码发现没有比赛,altough还有多的话,是完全一样的。对此有任何想法?

+0

你混淆了你的文件和变量吗? 'word'变量似乎是从'text.txt'文件中读取的,而'line'是来自'words.txt',这似乎表明您需要将它们交换。 – andersschuller

+2

readlines在字符串的末尾用换行符返回行。你不会在''猫里面'找到''cat \ n''我的猫是黑色的\ n'' – jterrace

+0

'flist'是怎么制作的 – cmd

回答

0

首先将数据库中的单词保存为set,然后将str.stripstr.lower应用于它们。 str.strip将删除前导和尾随空白字符,如'\n'等。

设置提供O(1)查找,并且设置交点将比您当前的O(n^2)方法更有效率。

然后迭代单词文件中的每一行,并首先应用str.stripstr.lower,然后再在集合中搜索它。

with open(r"words.txt") as f1, open(r"text.txt", "r") as f2: 

    dlist = set(line.strip().lower() for line in f2) #set of words from database 
    for line in f1: 
     line = line.strip().lower()  #use strip to remove '\n' 
     words = set(line.split()) #use split to get the words from the line 
            #and convert it into a set 
     common_words = words & dlist #use set intersection to find common words 
     for word in common_words: 
      *trick* 

请更换f1f2适当来我很困惑哪一个数据库,其中一个是文本数据集。