如何从文本文件中提取数值并放入数组?

时间:2017-05-03 18:40:45

标签: python

我想编写代码来读取文本文件并从中提取数字值并放入数组中。我是新手,有谁知道怎么做?我会很感激。 这是文本文件: https://www.dropbox.com/s/ayinnc83poulhv7/Booklist.txt?dl=0

1 个答案:

答案 0 :(得分:0)

如果新行中的数字那么你可以这样轻松地做到:

更新1:根据评论中的建议添加了rstrip()。

更新2:添加了文件输出。

Python 3代码:

number_list = []
with open("a.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)
with open("output.txt","w") as out:
    for i in number_list:
        out.write(str(i)+"\n")
print("File output.txt is generated")

<强>输出:

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

<强> output.txt的:

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

<强> A.TXT:

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