The tuples inside the file:
('Wanna', 'O')
('be', 'O')
('like', 'O')
('Alexander', 'B')
('Coughan', 'I')
('?', 'O')
My question is, how to join two strings from the different tuples but in the same index with a condition?
For example in my case, i want to join string in [0] if [1] equal to 'B' and followed by 'I'
So the output will be like:
Alexander Coughan
This is my code but the output is not like i want which is it just printed "NONE":
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
here's a one line solution
Here's how I'd write this:
Here's why:
Your file consists of what appear to be
repr
s of Python tuples of two strings. That's a really bad format, and if you can change the way you've stored your data, you should. But if it's too late and you have to parse it,literal_eval
is the best answer.So, we turn each line in the file into a tuple by
map
pingliteral_eval
over the file.Then we use
pairwise
from theitertools
recipes to convert the iterable of tuples into an iterable of adjacent pairs of tuples.So, now, inside the loop,
p0
andp1
will be the tuples from adjacent lines, and you can just write exactly what you described: ifp0[1]
is'B'
and it's followed by (that is,p1[1]
is)'I'
,join
the two[0]
s.I'm not sure what you wanted to do with the joined string, so I just printed it out. I'm also not sure if you want to handle multiple values or just the first, so I put in a
break
.I hadn't seen @MykhayloKopytonenko's solution when I went to write mine, so mine is similar:
This outputs:
If you absolutely must have the result returned as a string, change the list comprehension to:
This takes advantage of the fact that, based on your criteria, the last element of your list of tuples will never be returned as the first element of the result set. As a result, the
zip
effectively steps you through(tuples[n], tuples[n + 1])
so that you can easily examine the values.I'll extend the input data to include more
'B' + 'I'
examples.The result is: