python - 抓住一个或两个单词 IF 在一个模式后大写并将结果与另一个列表匹配
问题描述
我需要从文本中提取具有诸如 Lord|Baroness|Lady|Baron 等标题的唯一名称,并将其与另一个列表匹配。我努力获得正确的结果,希望社区可以帮助我。谢谢!
import re
def get_names(text):
# find nobel titles and grab it with the following name
match = re.compile(r'(Lord|Baroness|Lady|Baron) ([A-Z][a-z]+) ([A-Z][a-z]+)')
names = list(set(match.findall(text)))
# remove duplicates based on the index in tuples
names_ = list(dict((v[1],v) for v in sorted(names, key=lambda names: names[0])).values())
names_lst = list(set([' '.join(map(str, name)) for name in names_]))
return names_lst
text = 'Baroness Firstname Surname and Baroness who is also known as Lady Anothername and Lady Surname or Lady Firstname.'
names_lst = get_names(text)
print(names_lst)
现在产生:['Baroness Firstname Surname']
期望的输出:['Baroness Firstname Surname', 'Lady Anothername']
但不是Lady Surname
或Lady Firstname
然后我需要将结果与此列表匹配:
other_names = ['Firstname Surname', 'James', 'Simon Smith']
并从中删除元素'Firstname Surname'
,因为它与“所需输出”中男爵夫人的名字和姓氏相匹配。
解决方案
我建议你以下解决方案:
import re
def get_names(text):
# find nobel titles and grab it with the following name
match = re.compile(r'(Lord|Baroness|Lady|Baron) ([A-Z][a-z]+)[ ]?([A-Z][a-z]+)?')
names = list(match.findall(text))
# keep only the first title encountered
d = {}
for name in names:
if name[0] not in d:
d[name[0]] = ' '.join(name[1:3]).strip()
return d
text = 'Baroness Firstname Surname and Baroness who is also known as Lady Anothername and Lady Surname or Lady Firstname.'
other_names = ['Firstname Surname', 'James', 'Simon Smith']
names_dict = get_names(text)
print(names_dict)
# {'Baroness': 'Firstname Surname', 'Lady': 'Anothername'}
print([' '.join([k,v]) for k,v in names_dict.items()])
# ['Baroness Firstname Surname', 'Lady Anothername']
other_names_dropped = [name for name in other_names if name not in names_dict.values()]
print(other_names_dropped)
# ['James', 'Simon Smith']
推荐阅读
- swift - 使用 GeometryReader 绘制形状
- python - 最小化力的最佳轨迹,最终条件问题
- javascript - 在 Firebase 云函数中批量处理 Promise
- java - 出于某种原因,共享首选项默认为 true
- scala - 如何在 Intellij 的 Scala 中运行 Main 方法
- c# - 如何从另一个程序集将 DBContext 添加到服务
- c# - EF Core 数据为空
- c - 如何在 $PATH 中添加和删除名称?
- sql - Oracle:当一列中的值更改时选择行
- c - 使用 fwrite() 在 C 中使用 unsigned short 将二进制文件写入文件