在字符串比较中集成通配符

时间:2016-04-12 21:13:51

标签: python python-3.x

我有一个python脚本,它接受一个名称,重新格式化它,然后将它与其他名称列表进行比较,以查看它匹配的次数。问题是它被比较的名称有中间名首字母(我不想在脚本中输入)。

 list_of_names = ['Doe JM', 'Cruz CR', 'Smith JR', 'Doe JM', 'Maltese FL', 'Doe J']

现在我有一个简单的函数来重新格式化名称。

f_name = name_format('John','Doe')
print(f_name)

> 'Doe J'

现在我想进行比较,每当“Doe J”或“Doe JM”出现时,值为true。以下功能无法按预期工作。

def matches(name, list):
    count = 0
    for i in list:
        if i == name:
           count = count + 1
        else:
           pass
     return(count)

print (matches(f_name, list_of_names))

> 1

我的目标是使回报等于3.为了做到这些,我想忽略中间的首字母,在这种情况下,在'Doe JM'中将是'M'。

我想要做的是将名称格式化为'Doe J?'在哪里'?'是一张外卡。我尝试导入fnmatch并重新使用他们的一些工具但是没有成功。

2 个答案:

答案 0 :(得分:1)

使用两个用于 yield 。函数将返回重复值,您需要使用 set 删除它:

list_of_names = ['Doe JM', 'Cruz CR', 'Smith JR', 'Doe JM', 'Maltese FL', 'Doe J']

# List of names
def check_names(part_names, full_name_list):
    for full_name in full_name_list:
        for part_name in part_names:
            if part_name in full_name:
                yield full_name

result = set(check_names(['Doe J', 'Cruz'], list_of_names))

# One name 
def check_names(name, full_name_list):
    for full_name in full_name_list:
        if name in full_name:
            yield full_name

result = check_names('Doe J', list_of_names)

print list(result)  # List of result
print len(result)  # Count of names

答案 1 :(得分:0)

您使用re模块走在正确的轨道上。我相信你问题的解决方案是:

import re
def matches(name, name_list):
    regex = name + '\w?' # Allows one addition word character after the name
    result = list(map(lambda test_name: re.match(regex, test_name) is not None, name_list))
    return result.count(True)

print(matches(f_name, list_of_names))
# 3

此解决方案确保在名称后只允许使用一个字母数字字符。