我有一个文件名exclusionlist.txt,我的内容就像
import os
import re
import subprocess
......and many more
我有另一个名为libraries.txt的文件,该文件的内容是
import mymodule
import empmodule,os
import subprocess
import datetime,logging,re
.......and many more
我的问题是,从python如何知道exludelist.txt中的内容也存在于libraries.txt中,因为这里混淆了..
f = open('exclusionlist.txt', 'r')
f.read()
f1= open('libraries.txt', 'r')
f1.read()
if (//Is contents of f1 present in f2):
print libraries found
else:
print not found
f.close()
f1.close()
答案 0 :(得分:1)
使用set intersection:
def readImports(path):
with open(path) as f:
for line in f:
# lines of form "import ___,___"
# assuming not of form "from ___ import ___ [as ___]"
if 'import' in line:
modules = line.split('import')[1]
for module in modules.split(','):
yield module.strip()
linesInExclusion = set(readImports('exclusionlist.txt'))
linesInLibraries = set(readImports('libraries.txt'))
print(linesInExclusion.intersection(linesInLibraries))
如果你想要完美,你可以做return (line.strip() for line in f if line.strip()!='')
......