如何使用Python从文件的一部分生成整数列表?

2024-04-29 11:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件如下所示:

@ junk
...
@ junk
    1.0  -100.102487081243
    1.1  -100.102497023421
    ...   ...
    3.0  -100.102473082342
&
@ junk
...

我只对@&字符之间的两列数字感兴趣。这些字符可能出现在文件中的任何其他位置,但决不会出现在数字块中。你知道吗

我想创建两个列表,一个包含第一列,另一个包含第二列。你知道吗

List1 = [1.0, 1.1,..., 3.0]
List2 = [-100.102487081243, -100.102497023421,..., -100.102473082342]

我一直在使用shell脚本为这些文件准备一个更简单的Python脚本,它可以生成列表,但是,我正在尝试将这些进程迁移到Python上,以获得更一致的应用程序。有什么想法吗?我在Python和文件处理方面的经验有限。你知道吗

编辑:我应该提到,这个数字块出现在文件的两个地方。两个数字块是相同的。你知道吗

Edit2:一个通用函数将是最令人满意的,因为我将把它放入一个自定义库中。你知道吗

当前努力

我目前使用一个shell脚本将除数字块之外的所有内容修剪成两个独立的列。从这里开始,我可以使用以下函数

def ReadLL(infile):
    List = open(infile).read().splitlines()
    intL = [int(i) for i in List]
    return intL

从我的主打电话

import sys
import eLIBc
infile = sys.argv[1]
sList = eLIBc.ReadLL(infile)

问题在于知道如何用Python从原始文件中提取数字块,而不是使用shell脚本。你知道吗


Tags: 文件函数import脚本列表sys数字shell
2条回答

您需要循环文件本身,并为找到第一行而没有@字符时设置一个标志,之后就可以开始收集数字了。在一行中找到&字符时中断阅读。你知道吗

def readll(infile):    
    with open(infile) as data:
        floatlist1, floatlist2 = [], []
        reading = False

        for line in data:
            if not reading:
                if '@' not in line:
                    reading = True
                else:
                    continue

            if '&' in line:
                return floatlist1, floatlist2

            numbers = map(float, line.split())
            floatlist1.append(numbers[0])
            floatlist2.append(numbers[1])

因此,上述:

  • 将“reading”设置为False,并且仅当找到没有'@'的行时,才将该行设置为True。你知道吗
  • 当“reading”为True时:
    • 如果行包含&,则返回读取的数据
    • 否则,假定该行包含两个由空格分隔的浮点值,这些浮点值被添加到各自的列表中

通过返回,函数结束,文件自动关闭。只读取第一个块,忽略文件的其余部分。你知道吗

试试这个:

with open("i.txt") as fp:
    lines = fp.readlines()
    data = False
    List1 = []
    List2 = []
    for line in lines:
        if line[0] not in ['&', '@']:
            print line
            line = line.split()
            List1.append(line[0])
            List2.append(line[1])
            data = True
        elif data == True:
            break

print List1
print List2

这应该给你第一组数字。你知道吗

输入:

@ junk
@ junk
1.0  -100.102487081243
1.1  -100.102497023421
3.0  -100.102473082342
&
@ junk
1.0  -100.102487081243
1.1  -100.102497023421

输出:

['1.0', '1.1', '3.0']
['-100.102487081243', '-100.102497023421', '-100.102473082342']

更新

如果两个块都需要,请使用以下命令:

with open("i.txt") as fp:
    lines = fp.readlines()
    List1 = []
    List2 = []
    for line in lines:
        if line[0] not in ['&', '@']:
            print line
            line = line.split()
            List1.append(line[0])
            List2.append(line[1])

print List1
print List2

相关问题 更多 >