在lis中添加两个字符串

2024-03-28 19:00:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个系统,它将以名称作为输入的多行字符串,并将这些行作为一个2d列表输出,其中包括名字和姓氏。我的问题是,名字和姓氏都可以作为输入。这可能会让人困惑,所以我下面有一个例子。在

这是python3.6中的。在

我有个名字的名单:

Bob
Steve
Ted
Blake
Harry
Edric
Tommy
Bartholomew

还有一张姓氏名单:

^{pr2}$

输入

"""Bob Fischer Steve Ted Stinson Blake Harry McCord
Edric Bone Tommy Harvey Bartholomew"""

输出

[["Bob Fischer","Steve","Ted Stinson","Blake","Harry McCord"],
["Edric Bone","Tommy Harvey","Bartholomew"]]

我很难区分一组名字(Steve Ted)和第一个和姓氏之间的空格。在

有人能帮忙吗?我真的被卡住了。。。在


Tags: tommy名字stevebobblake名单ted姓氏
3条回答

您似乎希望匹配一个名字,该名字后面有空格和姓氏。在

您可以从您拥有的名称列表中创建一个regex模式,并使用re.findall查找所有不重叠的实例:

import re
first = ['Bob','Steve','Ted','Blake','Harry','Edric','Tommy','Bartholomew']
surnames = ['Fischer','Stinson','McCord','Bone','Harvey']
r = r"\b(?:{})\b(?:\s+(?:{})\b)?".format("|".join(first),"|".join(surnames))
s = """Bob Fischer Steve Ted Stinson Blake Harry McCord
Edric Bone Tommy Harvey Bartholomew"""
print(re.findall(r, s))
# => ['Bob Fischer', 'Steve', 'Ted Stinson', 'Blake', 'Harry McCord', 'Edric Bone', 'Tommy Harvey', 'Bartholomew']

参见Python demo

regex that is generated with this code

^{pr2}$

基本上,\b(?:...)\b(?:\s+(?:...)\b)?将备选方案中的一个名字作为一个整词进行匹配(由于\b围绕第一个(?:...)分组结构),然后(?:\s+(?:...)\b)?匹配1个或0个1+空格(?)的量词,后跟任何一个姓氏(同样,由于尾随的\b,作为整词)。在

试试这个,我用了(而不是姓和名)一个名词和它们所属的类别。在

A = [ 'Beaver' , 'Strawberry']
B = [ 'Animal' , 'Fruit']

input_string = 'Beaver Animal Strawberry Strawberry Fruit'
input_string = input_string.split(' ')

def combinestring( x_string ):
    compiling_string = []

    for i,x in enumerate(x_string):

        if (i+1) < len(x_string):
            if x in A and x_string[i+1] in B:
                compiling_string.append(x + ' ' + x_string[i+1])
            elif x in A:
                compiling_string.append(x)

        elif (i+1) == len(x_string) and x in A:
            compiling_string.append(x)

    return compiling_string



print combinestring(input_string)
#>>> ['Beaver Animal','Strawberry','Strawberry Fruit']
In [21]: first_names
Out[21]: ['Bob', 'Steve', 'Ted', 'Blake', 'Harry', 'Edric', 'Tommy', 'Bartholomew']

In [22]: surnames
Out[22]: ['Fischer', 'Stinson', 'McCord', 'Bone', 'Harvey']

In [23]: inp = """Bob Fischer Steve Ted Stinson Blake Harry McCord
    ...: Edric Bone Tommy Harvey Bartholomew""".split()

In [24]: out = []
    ...: fullname = None
    ...: for name in inp:
    ...:     if name in first_names:
    ...:         if fullname:
    ...:             out.append(fullname)
    ...:         fullname = name
    ...:     elif name in surnames:
    ...:         fullname += ' ' + name
    ...: out.append(fullname)
    ...:

In [25]: out
Out[25]:
['Bob Fischer',
 'Steve',
 'Ted Stinson',
 'Blake',
 'Harry McCord',
 'Edric Bone',
 'Tommy Harvey',
 'Bartholomew']

相关问题 更多 >