Python 从文件中提取数字
所以,我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者这样:
输出:
Or this way:
Output:
您可以将文件中的所有数字收集到一个列表中,如下所示:
输出:
注意:
在OP的情况下可能不需要使用re,但是包含在这里是因为它允许输入文件中存在潜在的垃圾
You can gather all the numbers in the file into a list like this:
Output:
Note:
Use of re may be unnecessary in OP's case but included here because it allows for potential garbage in the input file