Skip to main content
 首页 » 编程设计

python之在 file_2 中搜索 file_1 中的单词

2024年10月25日12lyj

我需要有以下输出: 如果在文件 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 

我仍然得到 False,但是 file_1 中的一些单词在 file_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. 

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