假设文本内容是<L xxx <L xx, xx> xxxx >,是一个xxx,[xx,xx],xxxx构成的两层数组,该怎么写
时间: 2024-12-22 16:23:20 浏览: 50
对于这样的文本格式,你需要稍微调整一下之前的代码,因为现在有两个层次的数组。我们可以递归地处理这种情况。下面是一个更新后的版本,可以解析这种嵌套结构:
```python
def parse_nested_array(line, current_list=None):
if not line or line.startswith('>'):
return [] if current_list is None else current_list
if '<L' in line:
start_index = line.index('<L') + len('<L ')
end_index = line[start_index:].find('>')
inner_list = parse_nested_array(line[start_index:end_index])
rest_of_line = line[end_index+1:]
return [inner_list] + (parse_nested_array(rest_of_line) if '<L' in rest_of_line else [])
else:
elements = line.strip().split(',')
return [elements] + (parse_nested_array(line[len(elements)+2:]) if '<L' in line[len(elements)+2:] else [])
def txt_to_arrays(file_path):
with open(file_path, 'r') as file:
content = file.read()
return parse_nested_array(content)
# 使用方法
nested_arrays = txt_to_arrays('example.txt')
```
这段代码首先定义了一个辅助函数`parse_nested_array`,用于递归地处理每一行。如果遇到`<L`,它会找到内部数组并继续解析;如果没有,则将元素添加到当前列表。
现在,`txt_to_arrays`函数会返回一个二维列表,表示嵌套的数组结构:
```python
[
[['xxx'], [[['xx', 'xx']], 'xxxx']],
# 其他类似结构...
]
```
请注意,这个实现假设`</L>`总是紧跟在内层数组之后,如果实际情况有变化,你可能需要调整`parse_nested_array`函数中的正则表达式匹配部分。
阅读全文
相关推荐



















