从fi以不同方式写入的读取列表

2024-04-26 07:19:12 发布

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

我需要一种方法来读取列表存储在一个文件中的几种不同的方式。我试着考虑用户在文件中存储列表的所有方法,并正确地解释它。你知道吗

下面是一个示例输入文件,其中的列表编写方式不同。你知道吗

# in_file.dat

# List 1 (enclosing brackets, comma separated, spaces after commas)
[0.5, 0.2, 0.6, 0.9, 1.5]

# List 2 (enclosing parenthesis, comma separated, no spaces or some spaces after commas)
(0.5,0.2,0.6,0.9, 1.5)

# List 3 (enclosing keys, mixed commas and semi-colons, mixed no-spaces and spaces)
{0.5,0.2,0.6;0.9;1.5}

# List 4 (single item)
[0.6]

# List 5 (space separated elements)
[2.3 5. 0.6 1.2 0.0 3.1]

应将每一行正确解读为一个列表,从而产生:

ls_1 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_2 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_3 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_4 = [0.6]
ls_5 = [2.3, 5., 0.6, 1.2, 0.0, 3.1]

我阅读文件的通常方式是

# Read data from file.
with open('in_file.dat', "r") as f_dat:
    # Iterate through each line in the file.
    for line in f_dat:
        # Skip comments
        if not line.startswith("#") and line.strip() != '':
            # Read list stored in line.
            ls_X = ??

有什么通用方法可以用来强制python将行解释为列表吗?你知道吗


Tags: and文件方法in列表方式linels
3条回答

试试这个:

import re
with open('in_file.dat', "r") as f_dat:
    for line in f_dat:
      if not line.startswith("#") and line.strip() != '':
          parts = re.split('[, ;]', line[1:-1])  # removes first and last char
          ls_X = filter(lambda x: x!="", parts)  # removes any empty string 

如果您确定每一行只有一个数字序列,请使用re

import re
lines=[]
for l in f_dat:
    if l and l[0]!='#':
        lines.append([float(i) for i in re.findall('[0-9.]+',l)])
print lines

希望这就是你要找的。你知道吗

>>> file
'[0.5, 0.2, 0.6, 0.9, 1.5]\n(0.5,0.2,0.6,0.9, 1.5)\n{0.5,0.2,0.6;0.9;1.5}\n[0.6]\n[2.3 5. 0.6 1.2 0.0 3.1]'
>>> for line in file.split('\n'):
...     print re.split(r"[,\s;]\s*",re.sub(r"[{}()\[\]]",'',line))
... 
['0.5', '0.2', '0.6', '0.9', '1.5']
['0.5', '0.2', '0.6', '0.9', '1.5']
['0.5', '0.2', '0.6', '0.9', '1.5']
['0.6']
['2.3', '5.', '0.6', '1.2', '0.0', '3.1']

相关问题 更多 >