过滤作者精确匹配,无论大小写

  • 本文关键字:大小写 过滤 python
  • 更新时间 :
  • 英文 :


我有一个目录和图书的链表。我试图按作者进行过滤,并返回完全匹配的图书,但是,每当我运行它时,它都说我的图书类型没有这样的属性。我还尝试将作者姓名大写,以便它是一致的,并且即使输入是不同的大小写也会返回匹配

class Book:
def __init__(self, title, author, year):
if not isinstance(title, str):
raise Exception("title must be a string")
if not isinstance(author, str):
raise Exception("author must be a string")
if not isinstance(year, int):
raise Exception("year must be an integer")
self.title = title
self.author = author
self.year = year
def __eq__(self, other):
if isinstance(other, Book):
return self.title == other.title and 
self.author == other.author and 
self.year == other.year
return NotImplemented
def __repr__(self):
return f"{repr(self.title)} by {repr(self.author)} {self.year})"

class Catalog:
def __init__(self):
self.lst = []
def filter_by_author(self, author):
xs = self.lst.copy()
xs = [author.capitalize() for author in xs]
if author.upper() in xs:
return self.lst
# driver
b1 = Book("1984", "George Orwell", 1949)
b2 = Book("Brave new world", "Aldous Huxley", 1932)
b3 = Book("El aleph", "Jorge Louis Borges", 1949)
b4 = Book("The devils of Loudun", "Aldous Huxley", 1952)
cat = Catalog()
cat.add(b1)
cat.add(b2)
cat.add(b3)
cat.add(b4)

la = cat.filter_by_author("aldous huxley")
assert la == [b2, b4]

我试图断言如果作者匹配目录中的书,列表将返回这些书

您不需要复制列表,因为下面的生成器会生成一个新列表。我也不明白你为什么要用.capitalize()

问题在于,在您的list comprehension中,您通过每个book,将当前的Book称为"author",然后尝试大写author。然而,authorBook,不能大写。在您的代码中,您需要调用author.author.capitalize(),或者您只需使用以下代码:

def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if book.author.lower() == author]

编辑回复评论

在python中,您可以很容易地检查字符串是否包含特定的子字符串:

def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if author in book.author.lower()]

我不确定,但这是你想要的,因为"John" in "Johnathan"是真的。所以你可能想要检查是否有名字是"John"

def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if author in book.author.lower().split()]

首先在某个字符串上分割字符串。如。"John Nathan Last-name".split(" ") == ["John", "Nathan", "Last-name"]参数的默认值是" ",所以你不需要传入它。

add()未定义。

str.capitalize()不同于str.upper()

不返回self。lst本身

class Catalog:
def __init__(self):
self.lst = []
def add(self, b):
self.lst.append(b)
def filter_by_author(self, author):
return [b for b in self.lst if b.author.upper() == author.upper()]

最新更新