gpt4 book ai didi

python - 如何解析由换行符分隔的文本

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:31 25 4
gpt4 key购买 nike

如何解析由换行符分隔的标记,如下所示:

Wolff PERSON
is O
in O
Argentina LOCATION

The O
US LOCATION
Envoy O
noted O

使用 python 转换成这样的完整句子?

Wolff is in Argentina
The US Envoy noted

最佳答案

您可以使用itertools.groupby为此:

>>> from StringIO import StringIO
>>> from itertools import groupby
>>> s = '''Wolff PERSON
is O
in O
Argentina LOCATION

The O
US LOCATION
Envoy O
noted O'''
>>> c = StringIO(s)
>>> for k, g in groupby(c, key=str.isspace):
if not k:
print ' '.join(x.split(None, 1)[0] for x in g)
...
Wolff is in Argentina
The US Envoy noted

如果输入实际上来自字符串而不是文件,则:

for k, g in groupby(s.splitlines(), key= lambda x: not x.strip()):
if not k:
print ' '.join(x.split(None, 1)[0] for x in g)
...
Wolff is in Argentina
The US Envoy noted

关于python - 如何解析由换行符分隔的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23083941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com