在file_2中搜索file_1中的单词

时间:2015-02-04 07:42:41

标签: python

我需要输出以下内容: 如果在文件2中找到文件1中的任何单词,则函数应返回True。否则函数应返回False: 在file_1中,每一行应包含一个单词。

def search_in_file(filepath_1, filepath_2):
    wordlist_1=[]
    f = open(filepath_1, "r")
    for line in f:
        wordlist_1.append(line)
    print wordlist_1

    wordlist_2=[]
    f = open(filepath_2, "r")
    for line in f:
        wordlist_2.append(line)
    print wordlist_2

    for i in wordlist_1:
        if i in wordlist_2:
            return True
        else:
            return False

我仍然是假的,但file_1中的一些单词在file_2中可见。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

您可以使用sets

def search_in_file(filepath_1, filepath_2):
    wordlist_1=set(open(filepath_1))
    wordlist_2=set(open(filepath_2))
    return wordlist_1 & wordlist_2 != set() # Check if set intersection is not empty
    # Of course, you could simply return wordlist_1 & wordlist_2,
    # that way you'd know the actual set of all matching words.

请注意,逐行读取文件时会保留行结尾。因此,如果文件的最后一行没有以换行符结尾,则可能会错过匹配。

答案 1 :(得分:0)

def search_in_file(filepath_1, filepath_2):
 wordlist_1=[]
 f = open(filepath_1, "r")
 for line in f:
     wordlist_1.append(line)
 print wordlist_1

 wordlist_2=[]
 f = open(filepath_2, "r")
 for line in f:
     wordlist_2.append(line)
 print wordlist_2

 for i in wordlist_1:
     if i in wordlist_2:
         return True
 return False

答案 2 :(得分:0)

  1. 使用with语句,openread方法获取文件内容。
  2. 使用split()方法创建list文件内容。
  3. 使用set方法从两个列表中获取常用值
  4. 输入:

    文件:“/ home / vivek / Desktop / input1.txt”

    file first 
    I have some word from file second
    Good
    1 2 3 4 5 6 7
    

    文件:“/ home / vivek / Desktop / input2.txt”

    file second 
    I have some word from file first
    Good 
    5 6 7 8  9 0
    

    代码:

    def searchInFile(filepath_1, filepath_2):
        with open(filepath_1, "r") as fp:
            wordlist_1 = fp.read().split()
    
        with open(filepath_2, "r") as fp:
            wordlist_2 = fp.read().split()
    
        common = set(wordlist_1).intersection(set(wordlist_2))
    
        return list(common)
    
    
    filepath_1 = "/home/vivek/Desktop/input1.txt"
    filepath_2 = "/home/vivek/Desktop/input2.txt"
    
    result = searchInFile(filepath_1, filepath_2)
    print "result:", result
    if result:
        print "Words are common in two files."
    else:
        print "No Word is common in two files."
    

    输出:

    infogrid@infogrid-172:~$ python  workspace/vtestproject/study/test.py
    result: ['Good', 'word', 'file', 'I', 'have', 'some', 'second', '5', '7', '6', 'from', 'first']
    Words are common in two files.