读取文本文件和拆分数字

Reading text file and splitting numbers

我目前有一个正在阅读的文本文件,其中包含 6 个我需要能够单独呼叫的号码。

文本文件看起来像这样

11 12 13

21 22 23

到目前为止,我已经使用以下方法尝试获得正确的输出,但没有成功。

with open(os.path.join(path,"config.txt"),"r") as config:
    mylist = config.read().splitlines() 
    print mylist

这给了我 ['11 12 13', '21 22 23'].

with open(os.path.join(path,"config.txt"),"r") as config:
    contents = config.read()
    params = re.findall("\d+", contents)
    print params

这给了我 ['11', '12', '13', '21', '22', '23']

with open(os.path.join(path,"config.txt"),"r") as config:
    for line in config:
        numbers_float = map(float, line.split())
        print numbers_float[0]

这给了我 11.0 21.0

最后一种方法最接近,但在第一列中给出了两个数字,而不是一个。

另外,我是否可以用逗号分隔文本文件中的数字以获得相同或更好的结果?

感谢您的帮助!

你的最后一个很接近——你正在为每行中的每个数字创建一个浮点数列表;唯一的问题是您只使用第一个。您需要遍历列表:

with open(os.path.join(path,"config.txt"),"r") as config:
    for line in config:
        numbers_float = map(float, line.split())
        for number in numbers_float:
            print number

你也可以把事情弄平

with open(os.path.join(path,"config.txt"),"r") as config:
    splitlines = (line.split() for line in file)
    flattened = (numeral for line in splitlines for numeral in line)
    numbers = map(float, flattened)
    for number in numbers:
        print number

现在只是 a chain of iterator transformations 如果你愿意,你可以使链条更简洁:

with open(os.path.join(path,"config.txt"),"r") as config:
    numbers = (float(numeral) for line in file for numeral in line.split())
    for number in numbers:
        print number

…但我认为这实际上并没有更清楚,尤其是对新手而言。