Py学习  »  Python

在python中,在匹配字符串的特定模式之后获取数字

checkmate • 7 年前 • 2365 次点击  

我想得到所有匹配的数字(仅数字示例'0012--22')或包含一些文本的数字(示例'rf332'),这些文本与提供的字符串列表(代码中的“我的列表”)匹配。带有数字的文本将以一个或两个空格分隔的格式出现。提供样本输入文件供参考。

这是输入文件:

$cat input_file
some text before Expedien: 1-21-212-16-26 some random text
Reference RE9833 of all sentences.
abc
123
456
something blah blah Ref.: 
tramite  1234567
Ref.:
some junk Expedien N° 18-00777 # some new content
some text Expedien N°18-0022995 # some garbled content

脚本现在附加在下面:它目前只识别一个元素{tramite':'1234567'}

import re
import glob
import os

my_list = ['Ref.:', 'Reference', 'tramite', 'Expediente', 'Expediente No', 'Expedien N°', 'Exp.No', 'Expedien']

#open the file as input
with open('garb.txt','r') as infile:
  res = dict()
  for line in infile:  
    elems = re.split('(?::)?\s+', line)
    #print(elems)
    if len(elems) >= 2 :
      contains = False
      tmp = ''
      for elem in elems:  
        if contains:
          res.update({tmp : elem})
          print(res)
          contains = False
          break
        if elem in my_list:
          contains = True
          tmp = elem
  #print(res)

这是预期输出:

样本输出:

{'Expedien N°': '18-0022995'}
{'Expedien N°': '18-0022995'}
{'Expedien': '1-21-212-16-26'}
{'Reference' : 'RE9833'}

等等。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40065
文章 [ 2 ]  |  最新文章 7 年前