Get String From File and Put in a List

Viewed 52

How can I extract lines of code that start with Value=" and end with the first occurrence of " from a text file? Script below helps me get the 'Micr' and 'Ocr' lines I need, but I don't know how to extract the value fields from them, then put them in a paired list.

file.txt

My name is Chris
<Micr Side="FRONT" Value="49116949119"/>
<Ocr Side="FRONT" Value="1238796634" Name="OCR 1"/>
My favorite food is chicken
some random text here because there is a lot more.
My name is Ben
<Micr Side="FRONT" Value="949491"/>
<Ocr Side="FRONT" Value="19919616161" Name="OCR 1"/>
My favorite food is burgers

output:

[[49116949119, 1238796634], [949491,19919616161]]

script

def read_oxi_file(self, oxi_filepath):
    import re

    keywords = ['<Micr', 'Name="OCR 1"']
    exclude = ['Value="27','Value="/']
    for fp in oxi_filepath:
        with open(fp, 'r') as dat_file:
            data = dat_file.readlines()

file_details.read_oxi_file(oxi_filepath)
2 Answers

Is that what you want ?

list_item = []
items_ = []
with open('file.txt', 'r') as dat_file:
    data = dat_file.readlines()
    end_ = False
    for a in data:
        if '<Micr Side="FRONT" Value="' in a :
            item = a.replace('<Micr Side="FRONT" Value="','').replace('"/>','')
            items_.append(item)
        elif '<Ocr Side="FRONT" Value="' in a :
            item = a.replace('<Ocr Side="FRONT" Value="','').replace('" Name="OCR 1"/>','')
            items_.append(item)
            list_item.append(items_)
            items_= []
            print(item)

print(list_item)
from bs4 import BeautifulSoup as Soup

html = '''My name is Chris
<Micr Side="FRONT" Value="49116949119"/>
<Ocr Side="FRONT" Value="1238796634" Name="OCR 1"/>
My favorite food is chicken
some random text here because there is a lot more.
My name is Ben
<Micr Side="FRONT" Value="949491"/>
<Ocr Side="FRONT" Value="19919616161" Name="OCR 1"/>
My favorite food is burgers'''

text = Soup(html, 'lxml')
data = list(map(lambda x: x['value'], text.select('[side="FRONT"]')))
print(data)

Output:
['49116949119', '1238796634', '949491', '19919616161']
Related