来自文本文件和包含单词

时间:2017-06-30 08:27:33

标签: python python-3.x

文字档案:

InheritedFrom: abc@aol.com

InheritedAltFrom:  abc@aol.com

From:  CN=deepak sethi/O=MHI

INetFrom:  xwy.com

代码我用来提取只包含“From:”的行

import re

with open('abc.txt', 'r') as file:
         raw = file.readlines()

for line in raw :  
    if  re.search(r'/b' + "From:" + r'/b', line):              
        print (line)

期待: -

From: CN=deepak sethi/O=MHI

我不明白出了什么问题?

2 个答案:

答案 0 :(得分:2)

Regexp的字边界<mjml> <mj-body> <mj-container> <mj-section> <mj-column> <mj-text align="center"> This is a header </mj-text> </mj-column> </mj-section> <mj-section> <mj-column> <mj-text align="center"> Another Header </mj-text> </mj-column> </mj-section> </mj-container> </mj-body> </mjml> 一致,而不是\b

/b

输出:

with open('abc.txt', 'r') as f:
    for l in f.readlines():
        if re.search(r'\bFrom\b', l):
            print(l)

答案 1 :(得分:1)

import re

with open('abc.txt', 'r') as file:
     raw = file.readlines()

for line in raw :
    if re.search(r'^From:', line):
        print line

将解决您的问题