簡體   English   中英

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

[英]python iterate through list by string matching

我有一個字符串列表,如果我的列表中的字符串出現在文件名中,那么我希望python打開該文件。 問題是,我希望python按照字符串出現在我的列表中的順序打開文件。 我當前的代碼按照python想要的順序打開文件,只檢查列表中的字符串是否出現在文件名中。

dogs.html
cats.html
fish.html

蟒蛇

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:

或者首先創建所有文件的列表,然后在列表的每次迭代中過濾該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:

您可以創建一組匹配項:

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

然后過濾您的列表

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

你可以通過重復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

您可以使用os.listdir和glob.fnmatch來分解重復的文件系統訪問,以防您處理數千個文件。

我會做這樣的事情:

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