python 不区分大小写的作者完全匹配过滤器

vlf7wbxs  于 2022-11-21  发布在  Python
关注(0)|答案(2)|浏览(162)

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

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]

我试图Assert,如果作者与目录中的书籍匹配,列表将与书籍一起返回

k3fezbri

k3fezbri1#

你不需要复制你的lst,因为你下面的生成器会生成一个新的列表。我也不明白你为什么要用.capitalize()
问题是在你的list comprehension中,你遍历每个book,调用当前的Book"author",然后尝试将author大写。然而author是一个Book,你不能将其大写。在你的代码中,你需要调用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"是True。

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"]参数的默认值是" ",所以你不需要传入它。

jhkqcmku

jhkqcmku2#

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()]

相关问题