我如何按作者对书籍的文本文件进行按字母顺序排列

时间:2014-10-23 03:58:21

标签: python-3.x

infile = open("Test100.txt","r")
lines = infile.readlines()
lines.sort()
print("Alphabetical by Title\n")
for line in lines:
    print(line)

我能够按标题按字母顺序打印给我(列表更长但是这里有一对): 散文中的圣诞颂歌;查尔斯狄更斯(6194)作为圣诞节的鬼故事

玩偶之家:亨利克·易卜生的戏剧(10282)

Jonathan Swift(7610)提出的适度建议

亚瑟柯南道尔(5909)在血色中的研究

查尔斯狄更斯的双城记(12676)

因为我试图按姓氏,名字,中间名(如果存在)或首字母进行按字母顺序排列。如何绕过有两位作者的书呢?

在python中有一个简单的方法来编号我的输出吗?

以下是文本文件中组织方式的示例:

Pride and Prejudice by Jane Austen (39395)
Adventures of Huckleberry Finn by Mark Twain (29760)
The Yellow Wallpaper by Charlotte Perkins Gilman (29382)
Beowulf (28881)
Alice's Adventures in Wonderland by Lewis Carroll (28474)
The Prince by Niccolò Machiavelli (19347)
The Adventures of Sherlock Holmes by Arthur Conan Doyle (18868)
Metamorphosis by Franz Kafka (18428)
Grimms' Fairy Tales by Jacob Grimm and Wilhelm Grimm (17271)
Les Misérables by Victor Hugo (15149)

1 个答案:

答案 0 :(得分:1)

import re
def cmpauthors(b1,b2):
    a1 = re.search("by (.*) \(\d+\)", b1)
    if a1 == None:
        return -1
    a2 = re.search("by (.*) \(\d+\)", b2)
    if a2 == None:
        return 1
    return cmp(a1.group(1),a2.group(1))

infile = open("Test100.txt","r")
lines = infile.readlines()
lines.sort(cmp=cmpauthors)
print("Alphabetical by Authors\n")
for line in lines:
    print(line)