首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果模式在Python中匹配,则从文件中提取数据。

如果模式在Python中匹配,则从文件中提取数据。
EN

Stack Overflow用户
提问于 2015-03-05 11:30:25
回答 2查看 41关注 0票数 1

在保存数据的文件中:

代码语言:javascript
复制
startTc:TC9

Client-1
IPAddress:10.203.205.111
Port:22
endTc:TC9

------------------------------------------------
startTc:TC5
Client-2
IPAddress of Client-2:10.203.205.112
Port:23
endTc:TC5
------------------------------------------------

如果startTc:TC5的条件匹配,则

代码语言:javascript
复制
Client-2
IPAddress of Client-2:10.203.205.112
Port:23

需要像端口中的23那样提取文件:当它看到endTc:TC5时,文件读取需要关闭

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-05 11:44:52

一种方法是使用regex,在下面的模式中,我使用正面环顾来匹配startTc:TC5\n\nendTc:TC5之间的字符串,然后您可以使用\n拆分结果

代码语言:javascript
复制
>>> s="""startTc:TC9
... 
... Client-1
... IPAddress:10.203.205.111
... Port:22
... endTc:TC9
... 
... ------------------------------------------------
... startTc:TC5
... Client-2
... IPAddress of Client-2:10.203.205.112
... Port:23
... endTc:TC5
... ------------------------------------------------"""
>>> re.search(r'(?<=startTc:TC5\n).*(?=\nendTc:TC5)',s,re.DOTALL).group(0).split('\n')
['Client-2', 'IPAddress of Client-2:10.203.205.112', 'Port:23']

请注意,如果您想从文件中读取此字符串,则需要在open('file_name').read()函数中使用s而不是s

票数 2
EN

Stack Overflow用户

发布于 2015-03-05 11:56:41

代码语言:javascript
复制
def getData(infilepath, start, end):
    with open(infilepath) as infile:
        data = []
        answer = []
        for line in infile:
            line = line.strip()
            if not line: continue
            if line == start or data:
                data.append(line)
            if line == end:
                temp = dict(data[1].split('-'))
                temp['ip'] = data[2].split(":")[1]
                temp['port'] = data[3].split(":")[1]
                answer.append(temp)
                data = []
    return answer

用法:

代码语言:javascript
复制
data = getData("path/to/file", "startTc:TC5", "endTc:TC5")
for d in data:
    print("Client:", d['Client'])
    print("IP:", d['ip'])
    print("Port:", d['port'])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28876856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档