小编use*_*978的帖子

匹配文件对象中的多行正则表达式

如何从文件对象(data.txt)中提取此正则表达式中的组?

import numpy as np
import re
import os
ifile = open("data.txt",'r')

# Regex pattern
pattern = re.compile(r"""
                ^Time:(\d{2}:\d{2}:\d{2})   # Time: 12:34:56 at beginning of line
                \r{2}                       # Two carriage return
                \D+                         # 1 or more non-digits
                storeU=(\d+\.\d+)
                \s
                uIx=(\d+)
                \s
                storeI=(-?\d+.\d+)
                \s
                iIx=(\d+)
                \s
                avgCI=(-?\d+.\d+)
                """, re.VERBOSE | re.MULTILINE)

time = [];

for line in ifile:
    match = re.search(pattern, line)
    if match:
        time.append(match.group(1))
Run Code Online (Sandbox Code Playgroud)

代码的最后一部分的问题是我逐行迭代,这显然不适用于多行正则表达式.我试过这样用pattern.finditer(ifile):

for match in pattern.finditer(ifile):
    print match
Run Code Online (Sandbox Code Playgroud)

...只是为了查看它是否有效,但是finditer方法需要一个字符串或缓冲区.

我也试过这种方法,但无法让它起作用

matches = [m.groups() for m …
Run Code Online (Sandbox Code Playgroud)

python regex multiline

11
推荐指数
1
解决办法
2万
查看次数

获取列表中每个键的字典值

假设我有一个清单:

a = ['apple', 'carrot']
Run Code Online (Sandbox Code Playgroud)

和字典:

d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
Run Code Online (Sandbox Code Playgroud)

如何使用列表a作为在字典d中查找的键?我希望将结果写入以逗号分隔的文本文件中

apple,    carrot
2,        44
4,        33
Run Code Online (Sandbox Code Playgroud)

更正了a = ['apple','orange']到a = ['apple','胡萝卜']的a-list

python dictionary

5
推荐指数
2
解决办法
2007
查看次数

标签 统计

python ×2

dictionary ×1

multiline ×1

regex ×1