在tex中查找特定的字符串对象

2024-06-08 00:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个自由的文本,里面充满了关于特定汽车、汽车品牌和其他自动相关信息的信息。我想从以下特定模板的文本中提取此信息:

  • 品牌:
  • 型号:
  • 颜色:

例如:“迈克和其他四个人开着一辆黑色奔驰车离开了。此外,他还在欧洲拥有一辆宝马M3。”

模板1:品牌:梅赛德斯,型号:-,颜色:黑色

模板2:品牌:宝马,车型:M3,颜色:-

在Python中解决这个问题的最佳方法是什么?虽然我对NLTK、词性标记和NP组块有一定的了解,但我认为只要我能识别出特定的术语,比如从包含列表的(嵌套)词典中,我就可以更容易地识别出这些术语。因此,它的行为就像一个受控制的词汇。在

希望有人能给我举个好榜样,或者能给我指明正确的方向。谢谢


Tags: 方法文本模板信息颜色汽车m3术语
1条回答
网友
1楼 · 发布于 2024-06-08 00:40:00

Assumption:

  1. You have a dictionary like this:
    Brand = ['Mercedes', 'BMW']
    Model = ['M3']
    Color = ['black']
  2. The three Keywords have allways the following order in the text:
    Color Brand Model

使用您的示例text,我得到了以下结果:

words = text.split(' ')
templates = []
for i, word in enumerate(words):
    if word in Brand:
        template = {'Brand': None, 'Model': None, 'Color': None}
        template['Brand'] = word
        if words[i-1] in Color:
            template['Color'] = words[i-1]
        if words[i+1] in Model:
            template['Model'] = words[i+1]

        templates.append( template )

print(templates)

[{'Brand': 'Mercedes', 'Model': None, 'Color': 'black'}, {'Brand': 'BMW', 'Model': 'M3', 'Color': None}]

相关问题 更多 >

    热门问题