gpt4 book ai didi

python - 改进 python 中的成员(member)比较

转载 作者:行者123 更新时间:2023-12-01 08:48:13 26 4
gpt4 key购买 nike

我正在尝试从杂志文章中提取所有名字和姓氏(我将其命名为 example.txt)。我分两部分来做。

在第一部分中,我提取一个由两个单词组成的字符串,每个单词都以大写字母开头,中间有一个空格,我使用正则表达式来执行此操作。我列出了所有这些字符串,并将其称为 all_names。这给了我所有可能的名字,比如“Barack Obama”,还有“The President”。

在第二部分中,我分割字符串并获取每个名字的第一部分,假设“Barack Obama”中的“Barack”,我想检查“Barack”是否在我准备的名字列表中提前(我将其命名为 first_names.txt)。如果存在匹配,并且仅当存在匹配时,我会将其添加到一个新数组中,该数组应该仅包含与 first_names.txt 中的名称匹配的名称。

因此理论上,“Barack Obama”会进入数组,而“The President”则不会。不幸的是,“The President”中的子字符串“The”出现在“Matthew”和“Katherine”等名字中,因此“The President”也会进入数组,尽管我不希望它这样做。我的代码如下。关于如何解决这个问题有什么建议吗?

import re 

text = open('example.txt').read()
first_names = open('first_names.txt').read()
regex = re.compile("[A-Z][a-z]+\s[A-Z][\w]*")
all_names = regex.findall(text)
array = []

for name in all_names:
first = name.split(" ")[0]
if first in first_names:
if name not in array:
array.append(name)
print(array)

最佳答案

您可以拆分 first_names 并创建这些名称的(假设文件中的名字由空格分隔):

first_names = set(open('first_names.txt').read().split())

然后if first in first_names将在O(1)时间内检查确切的名字是否在该集合中。这也将解决您排除“The President”的问题,因为first_names中的“The”将返回False

以下是一个简单示例:

first_names_text = "Barack Matthew Katherine"

first_names = set(first_names_text.split())
all_names = ['Barack Obama', 'The President', 'Katherine Swift']

array = []
for name in all_names:
first = name.split(" ")[0]
if first in first_names:
if name not in array:
array.append(name)

print(array)
# ['Barack Obama', 'Katherine Swift']

关于python - 改进 python 中的成员(member)比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com