简体   繁体   English

python通过字符串匹配迭代列表

[英]python iterate through list by string matching

I have a list of strings and if the string in my list appears in the filename then I want python to open the file. 我有一个字符串列表,如果我的列表中的字符串出现在文件名中,那么我希望python打开该文件。 The catch is, I want python to open the files in the order the string appears in my list. 问题是,我希望python按照字符串出现在我的列表中的顺序打开文件。 My current code opens the files in the order python wants and only checks if the string in the list appears in the filename. 我当前的代码按照python想要的顺序打开文件,只检查列表中的字符串是否出现在文件名中。

files

dogs.html
cats.html
fish.html

python 蟒蛇

list = ['fi', 'do', 'ca']
for name in glob.glob('*.html'):
  for item in list:
    if item in name:
      with open(name) as k:
lis = ['fi', 'do', 'ca']

for item in lis:
   for name in glob.glob('*.html'):
      if item in name:
         with open(name) as k:

or create a list of all files first, and then filter that list with every iteration of list : 或者首先创建所有文件的列表,然后在列表的每次迭代中过滤该list

>>> names=glob.glob('*.html')
>>> lis=['fi','do','ca']
>>> for item in lis:
...    for name in filter(lambda x:item in x,names):
...         with open('name') as k:

You can create a set of matches: 您可以创建一组匹配项:

matching_glob = set([name for name in glob.glob('*.html')])

and then filter your list 然后过滤您的列表

list_matching_glob = filter (lambda el: el in matching_glob) filter

You can do it a bit simpler by repeating the glob calls: 你可以通过重复glob调用来做到这一点:

names = ['fi', 'do', 'ca']
patterns = [s + "*.html" for s in names]

for pattern in patterns:
    for fn in glob.glob(pattern):
        with open(name) as k:
            pass

You can factor out the repeated file system access by using os.listdir and glob.fnmatch, in case you process thousands of files. 您可以使用os.listdir和glob.fnmatch来分解重复的文件系统访问,以防您处理数千个文件。

I would do something like this: 我会做这样的事情:

filenames = glob.glob('*.html')

for my_string in my_strings:
    for fname in (filename for filename in filenames if my_string in filename):
        with open(fname) as fobj:
            #do something.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM