文件内的元组:
('Wanna', 'O')
('be', 'O')
('like', 'O')
('Alexander', 'B')
('Coughan', 'I')
('?', 'O')
我的问题是,如何使用条件连接来自不同元组但位于同一索引中的两个字符串?
例如,在我的例子中,如果 [1] 等于“B”并后跟“I”,我想在 [0] 中加入字符串
所以输出将是这样的:
Alexander Coughan
这是我的代码,但输出不是我想要的,它只是打印出来的
“没有任何”:
readF = read_file ("a.txt")
def jointuples(sentt, i):
word= sentt[i][0]
wordj = sentt[i-1][0]
nameq = sentt[i][1]
if nameq =='I':
temp= ' '.join (word + wordj)
return temp
def join2features(sentt):
return [jointuples(sentt, i) for i in range(len(sentt))]
c_joint = [join2features(s) for s in readF]
c_joint
我是这样写的:
from ast import literal_eval
from itertools import tee
def pairwise(iterable): # from itertools recipes
a, b = tee(iterable)
next(b, None)
return zip(a, b)
with open("a.txt") as f:
for p0, p1 in pairwise(map(literal_eval, f)):
if p0[1] == 'B' and p1[1] == 'I':
print(' '.join(p0[0], p1[0]))
break
原因如下:
您的文件包含以下内容repr
两个字符串的 Python 元组。这是一种非常糟糕的格式,如果您可以更改存储数据的方式,那么您应该这样做。但如果为时已晚,你必须解析它,literal_eval是最好的答案。
因此,我们将文件中的每一行转换为一个元组map
ping literal_eval
在文件上。
然后我们使用pairwise
来自itertools recipes将元组的可迭代转换为相邻元组对的可迭代。
所以,现在,在循环内部,p0
and p1
将是相邻行的元组,您可以准确地写出您所描述的内容:p0[1]
is 'B'
其后是(即p1[1]
is) 'I'
, join
他们俩[0]
s.
我不确定您想对连接的字符串做什么,所以我只是将其打印出来。我也不确定你是否想处理多个值或只是第一个值,所以我输入了一个break
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)