Найти число, присутствующее в строке внутри документа, если есть совпадение строк из списка строк - PullRequest
0 голосов
/ 05 марта 2019

У меня есть список строк.Если какое-либо слово в списке совпадает внутри строки в документе, я хочу получить на выходе соответствующее слово и число, которое будет присутствовать в строке, в основном после этого соответствующего слова.Слово и число в основном разделены space или :

Пример из документа:

Expedien: 1-21-212-16-26 

Мой список:

my_list = ['Reference', 'Ref.', 'tramite', 'Expedien']

Числа внутристрока для совпадающей строки может быть либо отделена -, либо, возможно, без.Пример: 1-21-22-45 или RE9833

В этом случае RE9833 должно приходить полностью (не только число), если внутри строки найдено подходящее слово из списка.

Какнаписать регулярное выражение в Python для этого.

1 Ответ

0 голосов
/ 05 марта 2019

Входной файл:

$cat input_file
Expedien: 1-21-212-16-26 #other garbage
Reference RE9833 #tralala
abc
123
456
Ref.: UV1234
tramite  1234567
Ref.:

Образец:

import re

my_list = ['Reference', 'Ref.', 'tramite', 'Expedien']

#open the file as input
with open('input_file','r') as infile:
  #create an empty dict to store the pairs
  #that we will extract from the file
  res = dict()
  #for each input line
  for line in infile:
    #the only place we will use regex in this code
    #we split the input strings in a list of strings using
    #as separator : if present followed by some spaces
    elems = re.split('(?::)?\s+', line)
    #we test that we have at least 2 elements 
    #if not we continue with the following line
    if len(elems) >= 2 :
      contains = False
      #tmp will store all the keys identfied
      tmp = ''
      #we go through all the strings present in this list of strings
      for elem in elems:
        #when we enter this if we have already found the key and we have the value
        #at this iteration
        if contains:
          #we store it in the dict
          #reset the check and leave this loop
          res.update({tmp : elem})
          contains = False
          break
        #we check if the elem is in my_list
        if elem in my_list:
          #if this is the case
          #we set contains to true and we save the key in tmp
          contains = True
          tmp = elem
  print(res)

выход:

python find_list.py
{'tramite': '1234567', 'Reference': 'RE9833', 'Expedien': '1-21-212-16-26', 'Ref.': ''}

Regex demo: https://regex101.com/r/kSmLzW/3/

...