Python 从文件中提取数字

发布于 2025-01-11 12:24:53 字数 661 浏览 0 评论 0原文

所以,我有一个 txt 文件,其中包含一些 0 到 50 之间的整数。我想提取它们并使用它们的值。 txt 文件看起来像:

1 2 40 23

2 34 12

3 12 1

我尝试过类似的操作:

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

问题是我提取了两位数字,但我也提取了一位两位数字。

有什么解决办法吗?

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.
The txt file looks like:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦中的蝴蝶 2025-01-18 12:24:53

或者这样:

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)

输出:

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

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:

[1, 2, 40, 23, 2, 34, 12, 3, 12, 1]
一身骄傲 2025-01-18 12:24:53

您可以将文件中的所有数字收集到一个列表中,如下所示:

import re

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

输出:

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

注意:

在OP的情况下可能不需要使用re,但是包含在这里是因为它允许输入文件中存在潜在的垃圾

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:

[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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文