LIST内的正则表达式和模式匹配

时间:2016-06-16 07:13:50

标签: python list

我目前的工作目录中有一个文件名列表。

my_list = ["apple.txt","mango.txt", "grapes.txt","draw.png" , "hello123.txt" , "figure.png"]

现在我想创建一个仅存储*.txt个文件的新列表:

new_list = ["apple.txt","mango.txt", "grapes.txt", "hello123.txt"]

有没有办法在Python中使用正则表达式和模式匹配来实现这一点。

3 个答案:

答案 0 :(得分:3)

您可以使用:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 

503 Service Unavailable
    {
      "code": 503,
      "errors": [
        {
          "domain": "global",
          "message": "com.google.appengine.api.datastore.DatastoreNeedIndexException: no matching index found. recommended index is:\n- kind: Attendance\n  ancestor: yes\n  properties:\n  - name: date\n\nThe suggested index for this query is:\n    <datastore-index kind=\"Attendance\" ancestor=\"true\" source=\"manual\">\n        <property name=\"date\" direction=\"asc\"/>\n    </datastore-index>\n\n",
          "reason": "backendError"
        }
      ],
      "message": "com.google.appengine.api.datastore.DatastoreNeedIndexException: no matching index found. recommended index is:\n- kind: Attendance\n  ancestor: yes\n  properties:\n  - name: date\n\nThe suggested index for this query is:\n    <datastore-index kind=\"Attendance\" ancestor=\"true\" source=\"manual\">\n        <property name=\"date\" direction=\"asc\"/>\n    </datastore-index>\n\n"
    }

答案 1 :(得分:2)

方法1 regex

import re
txt_regex = re.compile(r'(\w+.txt)')
my_list = ["apple.txt","mango.txt", "grapes.txt","draw.png" , "hello123.txt" , "figure.png"]
result = [i for i in my_list if txt_regex.match(i)]

Demo正则表达式。

带有os

方法2

from os.path import splitext
result = [i for i in my_list if splitext(i)[1] == '.txt']
带有split

方法3

result = [i for i in my_list if i.split('.')[1] in '.txt']

<强>输出继电器

['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt']

答案 2 :(得分:1)

你也可以试试这个:

new_list = []
for file in my_list:
    if file.endswith(".txt"):
        new_list.append(file)
print(new_list)

输出

['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt']

更新:

您还可以使用defaultdict对所有文件进行分组,如下所示:

from collections import defaultdict

d = defaultdict(list)
for file in my_list:
    key = "." + file.split(".")[1]
    d[key].append(file)
print(d)

输出:

defaultdict(<class 'list'>, {'.txt': ['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt'], '.png': ['draw.png', 'figure.png']})

甚至没有默认用语:

d = {}
for file in my_list:
    key = "." + file.split(".")[1]
    if key not in d:
       d[key] = []
    d[key].append(file)
print(d)

输出:

{'.txt': ['apple.txt', 'mango.txt', 'grapes.txt', 'hello123.txt'], '.png': ['draw.png', 'figure.png']}