python - 合并单词对列表中的第一个单词,具体取决于这些对中的第二个单词

标签 python list python-3.x tuples grouping

我有一个程序(NLTK-NER),它为我提供了这个列表:

[
    ('Barak', 'PERSON'),
    ('Obama', 'PERSON'),
    ('is', 'O'),
    ('the', 'O'),
    ('president', 'O'),
    ('of', 'O'),
    ('United', 'LOCATION'),
    ('States', 'LOCATION'),
    ('of', 'LOCATION'),
    ('America', 'LOCATION')
]

如您所见,“Barak”和“Obama”是“PERSON”类型的单词,我想将它们(以及“LOCATION”类型的单词)合并在一起,如下所示:

['Barak Obama','is','the','president', 'of','United States of America']

如何解决这个问题?

最佳答案

本质上,我们在这里要做的就是将 classified_text 的一些项目分组在一起……因此,itertools.groupby() 是理所当然的。可以帮助。首先,我们需要一个关键函数,将带有标签 'PERSON''LOCATION' 的项目视为相似,并将所有其他项目视为不同。

这有点复杂,因为我们需要一种方法来区分具有相同标签的相邻项目('PERSON''LOCATION' 除外),例如('is', 'O'), ('the', 'O') 等。我们可以使用 enumerate()为此:

>>> list(enumerate(classified_text))
[..., (2, ('is', 'O')), (3, ('the', 'O')), (4, ('president', 'O')), ...]

现在我们知道要提供什么作为 groupby() 的输入,我们可以编写我们的关键函数:

def person_or_location(item):
    index, (word, tag) = item
    if tag in {'PERSON', 'LOCATION'}:
        return tag
    else:
        return index

请注意,赋值中的 index, (word, tag) 的结构与枚举列表中每个项目的结构相匹配。

一旦我们得到了这个,我们就可以编写另一个函数来进行实际的合并:

from itertools import groupby

def merge(tagged_text):
    enumerated_text = enumerate(tagged_text)
    grouped_text = groupby(enumerated_text, person_or_location)
    return [
        ' '.join(word for index, (word, tag) in group)
        for key, group in grouped_text
    ]

这是在行动:

>>> merge(classified_text)
['Barak Obama', 'is', 'the', 'president', 'of', 'United States of America']

关于python - 合并单词对列表中的第一个单词,具体取决于这些对中的第二个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579723/

相关文章:

python - 合并具有列表 init 的字典列表

python - 如何从另一个目录运行 Python pipenv?

python - TypeError : unsupported format string passed to NoneType.__format__(I do not know what this means)

python - 使用 urllib.request 验证 HTTPS 证书

python - Selenium 意外出现问题

python - 如何过滤阅读超过4本书的用户?

list - 将元素添加到子列表

c++ - 唯一形式算法和列表容器的唯一有什么区别?

python - 通过仅提供月份或仅提供星期几来创建日期时间对象

javascript - XMLHttpRequest 无法向 Flask 服务器发出请求