【问题标题】:Reading text file and splitting numbers读取文本文件并拆分数字
【发布时间】:2018-03-25 22:58:23
【问题描述】:

我目前有一个正在读取的文本文件,其中包含 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

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

我也可以用逗号分隔文本文件中的数字,结果相同或更好吗?

感谢您的帮助!

【问题讨论】:

  • 你想要的输出到底是什么?另外,为什么你标记了这个int,但在你的代码中使用了float?你想要哪一个? cloud9 标签有什么相关性?

标签: python string text int cloud9


【解决方案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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2016-08-01
    • 2016-04-11
    相关资源
    最近更新 更多