如何从文本文件中将包含字母的行提取到数组中?

时间:2017-05-10 18:11:35

标签: python

我想知道如何从文本文件中提取名称(字母)并将其放入数组中。文本文件是“书单”;它包含书籍和参考编号的名称,我想将书籍的名称提取到一个数组中。我知道怎么做参考数字而不是书名。如果有人可以帮助我,我会很感激。

这是文本文件: https://www.dropbox.com/s/ayinnc83poulhv7/Booklist.txt?dl=0

The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
10
Treasure Island
12
The Secret Garden
14
Alice's Adventures in Wonderland
20
Twenty Thousand Leagues Under the Sea
24
Peter Pan
26
Charlotte's Web
31
A Little Princess
32
Little Women
33
Black Beauty
35
The Merry Adventures of Robin Hood
40
Robinson Crusoe
46
Anne of Green Gables
50
Little House in the Big Woods
52
Swiss Family Robinson
54
The Lion, the Witch and the Wardrobe
56
Heidi
66
A Winkle in Time
100
Mary Poppins

这是我目前的代码:

number_list = []
#Put reference number into arrays
with open("Booklist.txt","r") as fp:
    line_list = fp.readlines()
    for line in line_list:
        line = line.rstrip()
        try:
            number_list.append(int(line))
        except:
            pass
print(number_list)

输出:

[2, 4, 6, 10, 12, 14, 20, 24, 26, 31, 32, 33, 35, 40, 46, 50, 52, 54, 56, 66, 100]

但是我也想让它把书的名字也放到一个数组中;与第一个数组分开,如上所示。

2 个答案:

答案 0 :(得分:0)

您可以简单地使用except块,如下所示:

with open("Booklist.txt","r") as fp:
        line_list = fp.readlines()
        number_list = []
        name_list = []
        for line in line_list:
            line = line.rstrip()
            try:
                number_list.append(int(line))
            except:
                name_list.append(line)
        print number_list
        print name_list

答案 1 :(得分:0)

您可以使用isdigit()方法检查给定的行是否为数字。

with open("Booklist.txt","r") as fp:
    lines = fp.readlines()
number_list = [line.strip() for line in lines if line.strip().isdigit()]