简体   繁体   English

如何从python3中的文本文件中提取和读取数字

[英]How to extract and read numbers from a text file in python3

Suppose the text file (say, x.txt) is假设文本文件(比如 x.txt)是

= 0
< 1
= 2

I want the output to be [0, 1, 2] and ['=', '<', '='] .我希望输出为[0, 1, 2]['=', '<', '='] How can I achieve this in python3?我怎样才能在 python3 中实现这一点?

You can use python's open method to read the file可以使用python的open方法读取文件

First, make 2 lists首先,制作2个列表

nums = []
ops = []

Then, use the open method to read file and loop through the lines in the file while adding the operators and numbers to the list.然后,使用 open 方法读取文件并遍历文件中的行,同时将运算符和数字添加到列表中。

file = open(“x.txt”, “r”) 
for line in file:
    line = line.split()
    ops.append(line[0])
    nums.append(line[1])

Then print if wanted.如果需要,然后打印。

print(ops, nums)
a=[]
b=[]
with open("x.txt","r") as file:
    for line in file:
        a.append(line.split()[0])
        b.append(line.split()[1])
print (a)
print (b)

Very straight forward.非常直接。 Just make empty lists, iterate over lines in file using with open and readlines method.只需创建空列表,使用with open和 readlines 方法遍历文件中的行。 Append to the lists.附加到列表中。 Cheers.干杯。

#init lists 
nums = [] 
operators = []

#open file, iterate over lines, append values 
with open('x.txt', 'r') as f:
    for line in f.readlines():
        _line = line.split()
        nums.append(_line[1])
        operators.append(_line[0])

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

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