简体   繁体   English

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

[英]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"; 文本文件是“ 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 这是文本文件: 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: 您可以简单地使用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

You can use isdigit() method to check whether the given line is digit or not. 您可以使用isdigit()方法检查给定的行是否为digit。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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