简体   繁体   中英

How to extract the lines containing the letters into an array from a text file?

I would like to know how to extract the names (letters) from a text file and put it into an array. The text file is a "Booklist"; it contains names of books and reference numbers and I would like to extract the names of the books into an array. I know how to do the reference numbers but not the book names. if there's anyone can help me, I would appreciate it.

Here's the text file: 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

This is my current code:

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)

Output:

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

But I also want it to put the name of the books into an array too; separately from the first array as shown above.

You can simply use the except block as the following:

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

You can use isdigit() method to check whether the given line is digit or not.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM