如何使用Python连接来自不同元组的两个字符串但在同一索引中? [英] How to join two strings from different tuples but in the same index using Python?

查看:406
本文介绍了如何使用Python连接来自不同元组的两个字符串但在同一索引中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件中的元组:

 ('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?

例如在我的情况下,如果[1]等于'B'并且后跟'I'

For example in my case, i want to join string in [0] if [1] equal to 'B' and followed by 'I'

所以输出结果如下:

  Alexander Coughan

这是我的代码,但输出不像我想要的只是打印
NONE:

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 how I'd write this:

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






原因如下:


Here's why:

您的文件包含两个字符串的Python元组的 repr 。这是一个非常糟糕的格式,如果你可以改变你存储数据的方式,你应该这样做。但如果为时已晚并且你必须解析它,请 literal_eval 是最佳答案。

Your file consists of what appear to be reprs 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.

因此,我们将文件中的每一行转换为元组 map ping literal_eval 对文件。

So, we turn each line in the file into a tuple by mapping literal_eval over the file.

然后我们使用<$ c来自 <$ c $的$ c>成对 c> itertools recipes 将元组的可迭代转换为可迭代的相邻元组对。

Then we use pairwise from the itertools recipes to convert the iterable of tuples into an iterable of adjacent pairs of tuples.

所以,现在,里面循环, p0 p1 将是相邻行的元组,您可以准确地写出您所描述的内容:如果 p0 [1] 'B'并且后面跟着(即 p1 [1] is)'我'加入两个 [0] s。

So, now, inside the loop, p0 and p1 will be the tuples from adjacent lines, and you can just write exactly what you described: if p0[1] is 'B' and it's followed by (that is, p1[1] is) 'I', join the two [0]s.

我不确定你想对连接的字符串做什么,所以我把它打印出来。我也不确定你是想要处理多个值还是只是第一个,所以我输入 break

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.

这篇关于如何使用Python连接来自不同元组的两个字符串但在同一索引中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆