把一个文件所有内容为G20的行名列名整合成字典形式,在另外一个文件中以所有键对值匹配结果并输出
时间: 2024-05-15 08:19:22 浏览: 105
假设文件名为file1.txt,文件内容如下:
```
,USA,China,Japan,Germany,UK,France,India,Italy,Brazil,Canada
USA,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
China,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
Japan,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
Germany,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
UK,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
France,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
India,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
Italy,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
Brazil,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
Canada,G20,G20,G20,G20,G20,G20,G20,G20,G20,G20
```
假设要处理的文件名为file2.txt,文件内容如下:
```
USA
Japan
India
Brazil
```
以下是Python代码实现:
```python
# 读取文件1,将内容转换为字典形式
with open('file1.txt', 'r') as f1:
content = f1.read().splitlines()
headers = content[0].split(',')
data = content[1:]
g20_dict = {}
for row in data:
row_data = row.split(',')
country = row_data[0]
for idx, val in enumerate(row_data[1:]):
if val == 'G20':
g20_dict[(country, headers[idx+1])] = val
# 读取文件2,以键值对匹配结果并输出
with open('file2.txt', 'r') as f2:
for line in f2:
country = line.strip()
for header in headers[1:]:
if (country, header) in g20_dict:
print(f"{country}, {header}: {g20_dict[(country, header)]}")
```
输出结果:
```
USA, China: G20
USA, Japan: G20
USA, Germany: G20
USA, UK: G20
USA, France: G20
USA, India: G20
USA, Italy: G20
USA, Brazil: G20
USA, Canada: G20
Japan, USA: G20
Japan, China: G20
Japan, Germany: G20
Japan, UK: G20
Japan, France: G20
Japan, India: G20
Japan, Italy: G20
Japan, Brazil: G20
Japan, Canada: G20
India, USA: G20
India, China: G20
India, Japan: G20
India, Germany: G20
India, UK: G20
India, France: G20
India, India: G20
India, Italy: G20
India, Brazil: G20
India, Canada: G20
Brazil, USA: G20
Brazil, China: G20
Brazil, Japan: G20
Brazil, Germany: G20
Brazil, UK: G20
Brazil, France: G20
Brazil, India: G20
Brazil, Italy: G20
Brazil, Brazil: G20
Brazil, Canada: G20
```
阅读全文