使用正则表达式分隔文本/文本处理

问题描述 投票:0回答:2

我有一个段落,需要用特定的关键字列表分隔。

这里是文本(单个字符串):

"Evaluation Note: Suspected abuse by own mother. Date 3/13/2019 ID: #N/A Contact: Not Specified Name: Cecilia Valore Address: 189 West Moncler Drive Home Phone: 353 273 400 Additional Information: Please tell me when the mother arrives, we will have a meeting with her next Monday, 3/17/2019 Author: social worker"

因此,我想使用python根据变量名称分隔此段。变量名称包括“评估注释”,“日期”,“ ID”,“联系人”,“名称”,“地址”,“家庭电话”,“其他信息”和“作者”。我认为使用正则表达式看起来不错,但是我在正则表达式方面没有很多经验。

这是我想要做的:

import re

regex = r"Evaluation Note(?:\:)? (?P<note>\D+) Date(?:\:)? (?P<date>\D+)
ID(?:\:)? (?P<id>\D+) Contact(?:\:)? (?P<contact>\D+)Name(?:\:)? (? P<name>\D+)"

test_str = "Evaluation Note: Suspected abuse by own mother. Date 3/13/2019
ID: #N/A Contact: Not Specified Name: Cecilia Valore "

matches = re.finditer(regex, test_str, re.MULTILINE)

但是找不到任何模式。

python regex text-processing
2个回答
0
投票

您可能可以动态生成该正则表达式。只要参数的顺序是固定的。

我在这里尝试,它确实可以完成工作。它要拍摄的实际正则表达式类似于Some Key(?P<some_key>.*)Some Other Key(?P<some_other_key>.*),依此类推。

import re

test_str = r'Evaluation Note: Suspected abuse by own mother. Date 3/13/2019 ID: #N/A Contact: Not Specified Name: Cecilia Valore '
keys = ['Evaluation Note', 'Date', 'ID', 'Contact', 'Name']

def find(keys, string):
    keys = [(key, key.replace(' ', '_')) for key in keys] # spaces aren't valid param names
    pattern = ''.join([f'{key}(?P<{name}>.*)' for key, name in keys]) # generate the actual regex
    for find in re.findall(pattern, test_str):
        for item in find:
            yield item.strip(':').strip() # clean up the result

for find in find(keys, test_str):
    print(find)

哪个返回:

Suspected abuse by own mother.
3/13/2019
#N/A
Not Specified
Cecilia Valore

0
投票

您可以使用search来获取变量的位置并相应地解析文本。您可以轻松自定义它。

import re
en = re.compile('Evaluation Note:').search(text)
print(en.group())
d = re.compile('Date').search(text)
print(text[en.end()+1: d.start()-1])
print(d.group())
i_d = re.compile('ID:').search(text)
print(text[d.end()+1: i_d.start()-1])
print(i_d.group())
c = re.compile('Contact:').search(text)
print(text[i_d.end()+1: c.start()-1])
print(c.group())
n = re.compile('Name:').search(text)
print(text[c.end()+1: n.start()-1])
print(n.group())
ad = re.compile('Address:').search(text)
print(text[n.end()+1: ad.start()-1])
print(ad.group())
p = re.compile('Home Phone:').search(text)
print(text[ad.end()+1: p.start()-1])
print(p.group())
ai = re.compile('Additional Information:').search(text)
print(text[p.end()+1: ai.start()-1])
print(ai.group())
aut = re.compile('Author:').search(text)
print(text[ai.end()+1: aut.start()-1])
print(aut.group())
print(text[aut.end()+1:])

这将输出:

评估说明:怀疑是自己母亲的虐待。

日期:3/13/2019

ID:#N / A

联系人:未指定

名称:塞西莉亚·瓦洛雷]

地址:西蒙克勒路189号

家庭电话:353 273 400

[附加信息:请告诉我母亲何时到来,我们将在下一个星期一2019/3/17与她开会

作者:社会工作者

我希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.