python - 在标题下查找文本的最佳方法是什么
问题描述
我正在做一个 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
我想要做的是从文本中提取name
and 。age
我想编写一个适用于两种格式的标记器/正则表达式。姓名和年龄可以在任何一行中。
目前,我想了解我可以使用的技术或库。我正在使用python-3.6,我很乐意使用任何库。
我目前的策略是: - 我打算用换行符分割每一行。- 然后对于每一行,我寻找(?: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)
但是它不适用于第二种格式。能否请您让我知道和想法。
解决方案
这些正则表达式可以为您工作:
"Name is (.+?)\b|Name\n?(.+?)\b"
"Age is (.+?)\b|Age\n?(.+?)\b"
您只需要注意检查不同的捕获组。
在这里检查它们。这同样适用于年龄。
推荐阅读
- ruby-on-rails - 将 ruby 从 1.9.3 升级到 2.2.10 时内存增加
- c++ - 如果您在抽象类中有一个 const 变量,那么继承的类是否会获得一个实例或指向基类常量的指针?
- javascript - 如何在 JavaScript 中的函数内制作自定义提示框?
- android - 应用链接验证不起作用
- javascript - 加入前瞻正则表达式并保留(所有)分隔符?
- java - Hibernate/JPA,如何实现关系变量?
- matlab - Matlab中非线性方程组描述的时间序列建模
- python - NLTK Wordnet 获取 Python 中的 Synset 列表
- assembly - 如何在汇编中获取字符串输入
- javascript - 将 next.js 与纱线工作区一起使用