简体   繁体   English

Python 从文件中提取数字

[英]Python Extract Numbers from a file

So, I have a txt file with some integers which are between 0 and 50. I want to extract them and to use their values.所以,我有一个 txt 文件,其中包含一些介于 0 和 50 之间的整数。我想提取它们并使用它们的值。 The txt file looks like: txt 文件如下所示:

1 2 40 23

2 34 12

3 12 1

I have tried something like:我试过类似的东西:

with open(input_file, "r") as file:
    lines = file.readlines()
    for i in range(len(lines)):
        l = lines[i].strip()
        for c in range(1, len(l)-1):
            if(l[c] >= '0' and l[c] <= '9' and (l[c+1] < '0' or l[c+1] > '9')):
                # other code with those numbers
            elif(l[c] >= '0' and l[c] <= '9' and (l[c+1] >= '0' and l[c+1] <= '9')):
                # other code with those numbers

The problem is that I extract the two digits numbers, but I do also extract one digit two digits numbers.问题是我提取了两位数,但我也提取了一位两位数。

Any solution?任何解决方案?

You can gather all the numbers in the file into a list like this:您可以将文件中的所有数字收集到一个列表中,如下所示:

import re

with open(input_file) as f:
    print(list(map(int, re.findall('\d+', f.read()))))

Output: Output:

[1, 2, 40, 23, 2, 34, 12, 3, 12, 1]

Note:笔记:

Use of re may be unnecessary in OP's case but included here because it allows for potential garbage in the input file在 OP 的情况下可能不需要使用re ,但包含在此处,因为它允许输入文件中存在潜在的垃圾

Or this way:或者这样:

my_array=[]
with io.open(inputfile, mode="r", encoding="utf-8") as f:             
    for line in f:
        my_array=my_array+line.split()
results = list(map(int, myarray)) #convert to int    
print(my_array)

Output: Output:

[1, 2, 40, 23, 2, 34, 12, 3, 12, 1]

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

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