首页 > 解决方案 > 在标题下查找文本的最佳方法是什么

问题描述

我正在做一个 NLP 项目,我有两种格式的输入文本。

格式一:

Some line
Some line
Name is <name> random text and numbers.  age is <age> random text and numbers
Some line

格式二:

Some line
Name
<name>. Random text and numbers
Some random line
Age
<age>.  random text and numbers

我想要做的是从文本中提取nameand 。age我想编写一个适用于两种格式的标记器/正则表达式。姓名和年龄可以在任何一行中。

目前,我想了解我可以使用的技术或库。我正在使用,我很乐意使用任何库。

我目前的策略是: - 我打算用换行符分割每一行。- 然后对于每一行,我寻找(?:names is) (\w). 第一个匹配是 - 名称。这适用于第一种格式。

我当前的名称代码是:

import re 
Pattern = '(?:names is) (\w)'
Text ='...'.split('\n')

for t in Text:    
  Match = re.match(pattern, Text, re.I)    

  if match.group(1) is not None:

      Name = match.group(1)

但是它不适用于第二种格式。能否请您让我知道和想法。

标签: pythonregexpython-3.xnlpnltk

解决方案


这些正则表达式可以为您工作:

"Name is (.+?)\b|Name\n?(.+?)\b"
"Age is (.+?)\b|Age\n?(.+?)\b"

您只需要注意检查不同的捕获组。

在这里检查它们。这同样适用于年龄。


推荐阅读