Python:使用python从一行中的数字开始写匹配的单词

时间:2018-08-06 03:39:49

标签: python file text-files

我想阅读文本文件,并在下面的文本中找到以5开头的单词。

16  16   011000   id    N16     Online      FC  F-Port  51:40:2e:c0:01:c9:53:e8
26  26   011a00   id    N16     Online      FC  F-Port  56:c9:ce:90:4d:77:c6:03
27  27   011b00   id    N16     Online      FC  F-Port  56:c9:ce:90:4d:77:c6:07
32  32   012000   id    N16     Online      FC  F-Port  51:40:2e:c0:01:c9:54:80
42  42   012a00   id    N16     Online      FC  F-Port  56:c9:ce:90:12:b4:19:01
43  43   012b00   id    N16     Online      FC  F-Port  56:c9:ce:90:12:b4:19:03

我在另一个文件中的输出应该是

51:40:2E:C0:01:C9:53:E8
51:40:2E:C0:01:C9:53:EA

但是当我写另一个文件时,它只写最后一个字。但是我需要写所有匹配的词。

这是我的代码:

import re
import sys
import os

with open('/root/SDFlex/work/cookbooks/Status2.txt', 'r') as file:
    for line in file :
        matchedLine = ("\n".join(list(filter(lambda x: x.startswith('56'),line.split(' ')))))
                print(matchedLine)

with open('/root/SDFlex/work/cookbooks/ilorest/files/file001.txt', 'w') as file:
    file.write(matchedLine)

4 个答案:

答案 0 :(得分:1)

您可以使用re并打开包装:

import re
new_data = [re.split('\s+', i.strip('\n')) for i in open('filename.txt')] 
final_results = [a for *_, a in new_data if a.startswith('51')]

输出:

['51:40:2e:c0:01:c9:53:e8', '51:40:2e:c0:01:c9:54:80']

Python 2解决方案(不解包):

final_results = [i[-1] for i in new_data if i[-1].startswith('51')]

答案 1 :(得分:0)

您要在matchedLine中存储最后一个匹配项,并覆盖它存储的所有先前匹配项。

您应该将匹配项存储在列表中,并继续向其中添加新的匹配项:

matches = []
with open('/root/SDFlex/work/cookbooks/Status2.txt', 'r') as file:
    for line in file :
        matches += list(filter(lambda x: x.startswith('56'),line.split()))

with open('/root/SDFlex/work/cookbooks/ilorest/files/file001.txt', 'w') as file:
    file.write('\n'.join(matches))

答案 2 :(得分:0)

由于您的格式是基于列的,所以最易读的方法是按照extract data at specific columns in a line if there is any data at them提取特定的列。

也不要过分热衷于将所有内容放入一行中-只会导致不可读的代码。

with open(<...>) as infile, open(<...>) as outfile:
    for line in infile:    # don't override `file` 'cuz it's a built-in type
        mac = line[56:79]
        if mac.startswith('5'):
            print(line)
            outfile.write(line)

对于一次性任务,grep就足够了:

$ grep -P '^.{56}5' infile >outfile

答案 3 :(得分:-1)

尝试一下:

with open('/root/SDFlex/work/cookbooks/Status2.txt', 'r') as file:
    l='\n'.join(i.split()[-1] for i in file if i.split()[-1].startswith('51'))
with open('/root/SDFlex/work/cookbooks/ilorest/files/file001.txt', 'w') as file:
    file.write(l)

/root/SDFlex/work/cookbooks/ilorest/files/file001.txt

51:40:2e:c0:01:c9:53:e8
51:40:2e:c0:01:c9:54:80

在您的问题中,您希望文件位于上方,因此请尝试以下操作:

with open('/root/SDFlex/work/cookbooks/Status2.txt', 'r') as file:
    l='\n'.join(i.split()[-1].upper() for i in file if i.split()[-1].startswith('51'))
with open('/root/SDFlex/work/cookbooks/ilorest/files/file001.txt', 'w') as file:
    file.write(l)

/root/SDFlex/work/cookbooks/ilorest/files/file001.txt

51:40:2E:C0:01:C9:53:E8
51:40:2E:C0:01:C9:53:EA