-4

我们有一个作业,我有一个严重的问题。关键是将每一行变成一个元组,并将这些元组变成一个列表。喜欢list=[tuple(line1),tuple(line2),tuple(line3),...]。此外,还有很多用逗号分隔的字符串,比如"aei","1433","lincoln",...

这是问题:

一本书可以表示为作者的姓氏、作者的名字、标题、日期和 ISBN 的元组。

  • 编写一个函数 ,readBook()给定一个包含此信息的逗号分隔字符串,返回一个表示该书的元组。

  • 编写一个函数 ,readBooks()给定包含每本书一个逗号分隔行的文本文件的名称,用于readBook()返回一个元组列表,每个元组描述一本书。

  • 编写一个函数 ,buildIndex()给定由 返回的书籍列表readBooks(),构建从关键字到书名的映射。关键词是书名中的任何单词,除了“a”、“an”或“the”。

这是我的代码:

RC=("Chann", "Robbbin", "Pride and Prejudice", "2013", "19960418")
RB=("Benjamin","Franklin","The Death of a Robin Thickle", "1725","4637284")
def readBook(lastName, firstName, booktitle, date, isbn):
    booktuple=(lastName, firstName, booktitle, date, isbn)
    return booktuple
# print readBook("Chen", "Robert", "Pride and Prejudice", "2013", "19960418")

def readBooks(file1):
    inputFile = open(file1, "r")
    lines = inputFile.readlines()
    book = (lines)
    inputFile.close()
    return book
print readBooks("book.txt")
BooklistR=[RC,RB]

def buildIndex(file2):
    inputFile= open("book.txt","r")
    Blist = inputFile.readlines()
    dictbooks={}
    for bookinfo in Blist:
        title=bookinfo[2].split()
        for infos in title:
            if infos.upper()=="A":
                title.remove(infos)
            elif infos.upper()=="THE":
                title.remove(infos)
            elif infos.upper()=="AN":
                title.remove(infos)
            else:
                pass
        dictbooks[tuple(title)]= bookinfo[2]
    return dictbooks
print buildIndex("book.txt")

#Queries#
def lookupKeyword(keywords):
    dictbooks=buildIndex(BooklistR)
    keys=dictbooks.viewkeys()
    values=dictbooks.viewvalues()
    for keybook in list(keys):
        for keyw in keywords:
            for keyk in keybook:
                if keyw== keyk:
                    printoo= dictbooks[keybook]
                else:
                    pass
    return printoo
print lookupKeyword("Robin")
4

2 回答 2

2

这样的事情有什么问题?:

with open(someFile) as inputFile:
    myListofTuples = [tuple(line.split(',')) for line in inputFile.readlines()]

[根据罗伯特的评论添加的解释]

第一行在with语句中打开文件。Pythonwith语句是一个相当新的特性,而且相当先进。设置一个上下文,在该上下文中执行代码,并保证在 Python 引擎退出该上下文时(无论是通过完成工作还是遇到未处理的异常)来执行清理和终结代码。

您可以在以下位置阅读有关丑陋的详细信息:Python Docs: Context Managers,但要点是我们打开someFile并保证在代码执行离开该上下文后它会正确关闭(套件语句之后的with语句。即使我们遇到一些错误,或者如果我们在该套件中的代码引发了一些我们未能捕获的异常,也会这样做。

在这种情况下,我们使用该as子句给我们一个本地名称,我们可以通过它来引用打开的文件对象。(文件名只是一个字符串,作为参数传递给open()内置函数......该函数返回的对象需要有一个我们可以引用它的名称。这类似于for i in whatever语句绑定每个项目的人通过循环的每次迭代的名称i

我们的语句套件with(即在上下文管理器的上下文中运行的一组缩进语句)由一个语句组成......一个绑定到 name 的列表推导myListofTuples

列表推导是另一个相当高级的编程概念。有许多非常高级的语言以各种方式实现它们。在 Python 的情况下,它们可以追溯到比with声明更早的版本 --- 我认为它们是在 2.2 左右的时间范围内引入的。

因此,列表推导式在 Python 代码中相当普遍,而with语句只是慢慢被采用。

Python 中的列表文字看起来像:[something, another_thing, etc, ...]列表推导式类似,但将项目文字列表替换为表达式,即一行代码,其计算结果为列表。例如:[x*x for x in range(100) if x % 2]是一个列表推导,它计算为一个整数列表,这些整数是 1 到 99 之间奇数的平方。(注意列表推导中没有逗号。一个表达式代替了逗号分隔的序列已在列表文字中使用)。

在我的示例中,我将for line in inputFile.readlines()其用作表达式的核心,并且将 common ( line.split(',')) 上的每个拆分,然后将结果列表转换为tuple().

这只是一种非常简洁的说法:

myListofTuples = list()
for line in inputfile.readlines():
    myListofTuples.append(line.split(','))
于 2013-07-19T03:51:00.493 回答
0

一种可能的程序:

import fileinput

def readBook(str):
    l = str.split(',')
    t = (l[0:5])
    return t

#b = readBook("First,Last,Title,2013,ISBN")
#print b

def readBooks(file):
    l = []
    for line in fileinput.input(file):
        t = readBook(line)
        # print t
        l.append(t)
    return l

books = readBooks("data")

#for t in books:
#    for f in t:
#        print f

def buildIndex(books):
    i = {}
    for b in books:
        for w in b[2].split():
            if w.lower() not in ('a', 'an', 'the'):
                if w not in i:
                    i[w] = []
                i[w].append(b[2])
    return i

index = buildIndex(books)

for w in sorted(index):
    print "Word: ", w
    for t in index[w]:
        print "Title: ", t

示例数据文件(代码中称为“数据”):

Austen,Jane,Pride and Prejudice,1811,123456789012X
Austen,Jane,Sense and Sensibility,1813,21234567892
Rice-Burroughs,Edgar,Tarzan and the Apes,1911,302912341234X

样本输出:

Word:  Apes
Title:  Tarzan and the Apes
Word:  Prejudice
Title:  Pride and Prejudice
Word:  Pride
Title:  Pride and Prejudice
Word:  Sense
Title:  Sense and Sensibility
Word:  Sensibility
Title:  Sense and Sensibility
Word:  Tarzan
Title:  Tarzan and the Apes
Word:  and
Title:  Pride and Prejudice
Title:  Sense and Sensibility
Title:  Tarzan and the Apes

请注意,由于嵌入了逗号,数据格式不支持“狮子、女巫和魔衣橱”等书名。如果文件是 CSV 格式,字符串周围有引号,那么它可以管理它。

我不确定这是完全最低限度的 Pythonic 代码(完全不确定),但它似乎确实符合要求。

于 2013-07-19T05:38:09.627 回答