python 遍历txt文本的多条数据,其中两条数据是123:[a,b],[c,d],453: [d,e],[d,e],最终输出[('123', [('a','b'), ('c','d')]) ,('453', [('d','e'), ('c','e')])]
时间: 2023-10-23 19:10:16 浏览: 27
可以使用正则表达式来解析文本,然后将结果存储在一个列表中:
```python
import re
text = '''
123:[a,b],[c,d]
453: [d,e],[d,e]
'''
data = []
pattern = r'(\d+):\s*\[(\w+),(\w+)\],\[(\w+),(\w+)\]'
for match in re.finditer(pattern, text):
num, a, b, c, d = match.groups()
data.append((num, [(a, b), (c, d)]))
print(data) # [('123', [('a', 'b'), ('c', 'd')]), ('453', [('d', 'e'), ('d', 'e')])]
```
解析过程中,使用了一个正则表达式模式来匹配文本中的每一行数据。模式中使用了分组来提取数据的不同部分,然后将它们存储在一个元组中。最后,将所有元组存储在一个列表中。
输出结果与题目所示的格式相同。
相关问题
python 遍历txt文本的多条数据,其中数据类型是123: [a,b],[c,d],最终输出[('123', [('a','b'), ('c','d')])] ,
假设txt文本中每行只有一条数据,可以使用以下代码实现:
```
result = []
with open('data.txt', 'r') as f:
for line in f:
data = line.strip().split(':')
key = data[0]
values = data[1].split(',')
sub_result = []
for value in values:
sub_data = value.strip('[]').split(',')
sub_result.append((sub_data[0], sub_data[1]))
result.append((key, sub_result))
print(result)
```
其中,假设txt文本中的数据格式为:`123: [a,b],[c,d]`,则代码中的`data = line.strip().split(':')`将数据按照冒号分隔开,并获取到key和values。接着,使用`values = data[1].split(',')`将values按照逗号分隔开,得到一个包含多个子数据的列表。然后,使用一个循环遍历每个子数据,将其按照逗号和方括号分隔开,并将分隔后的数据存入一个元组中。最后,将key和子数据列表组成一个元组,并添加到结果列表中。最终输出的结果即为`[('123', [('a','b'), ('c','d')])]`。
python 遍历txt文本的多条数据,其中数据是123:[a,b],[c,d],453: [d,e],[d,e],最终输出[('123', [('a','b'), ('c','d')]) ,('453', [('d','e'), ('c','e')])]
可以使用正则表达式来匹配每条数据,然后提取出需要的数据。
具体实现如下:
```python
import re
txt = '''123:[a,b],[c,d]
453: [d,e],[d,e]'''
# 使用正则表达式匹配每条数据
pattern = r'(\d+):\s*\[(\w+),(\w+)\],\[(\w+),(\w+)\]'
result = re.findall(pattern, txt)
# 将数据转换成需要的格式
output = []
for r in result:
key = r[0]
values = [(r[1], r[2]), (r[3], r[4])]
output.append((key, values))
print(output)
```
输出结果为:
```
[('123', [('a', 'b'), ('c', 'd')]), ('453', [('d', 'e'), ('d', 'e')])]
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)