读取文本文件和拆分数字

时间:2018-03-25 22:58:24

标签: python string text int cloud9

我目前有一个正在阅读的文本文件,其中包含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&#39 ;,' 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

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

我还能用逗号分隔文本文件中的数字是否具有相同或更好的结果?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你的最后一个是关闭的 - 你为每行中的每个数字创建一个浮动列表;唯一的问题是你只使用第一个。你需要遍历列表:

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

...但我不认为这实际上更清楚,特别是对新手而言。