You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TXT文件中的电话号码列表转换为JSON格式

问题描述

我有一个存储大量电话号码的.txt文件,需要将其转换为JSON格式以便存储并后续存入数组。该TXT文件内容格式如下:

phonenumber: value1
phonenumber: value2
phonenumber: value3

我尝试了以下代码,但未能得到正确格式:

f = open("phone+.txt", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
for v in splitcontent:
    l = v.split(': ')
    d.append(list(s.split(': ',1) for s in l))


with open("phone_list.json", "w") as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

得到的错误结果:

[
    [
        [
            "phonenumber"
        ],
        [
            "value1"
        ]
    ],
    [
        [
            "phonenumber"
        ],
        [
            "value2"
        ]
    ],
    [
        [
            "phonenumber"
        ],
        [
            "value2"
        ]
    ]
]
修正方案

问题根源

  1. 代码对split(': ')得到的键值对结果再次执行split操作,导致生成不必要的嵌套数组。
  2. 缺少import json语句,规范写法需要补充该导入。

正确代码

方案1:生成对象组成的数组(推荐,方便后续按键取值)

import json

# 用with语句自动管理文件,避免资源泄漏
with open("phone+.txt", "r") as f:
    splitcontent = f.read().splitlines()

phone_array = []
for line in splitcontent:
    # 按': '分割一次,直接得到键和值
    key, value = line.split(': ', 1)
    phone_array.append({key: value})

with open("phone_list.json", "w") as file:
    json.dump(phone_array, file, indent=4, sort_keys=False)

方案2:生成仅含电话号码值的数组(若键固定为phonenumber可简化)

import json

with open("phone+.txt", "r") as f:
    splitcontent = f.read().splitlines()

# 用列表推导式直接提取号码值
phone_array = [line.split(': ', 1)[1] for line in splitcontent]

with open("phone_list.json", "w") as file:
    json.dump(phone_array, file, indent=4)

正确JSON结果

方案1生成的结果:

[
    {
        "phonenumber": "value1"
    },
    {
        "phonenumber": "value2"
    },
    {
        "phonenumber": "value3"
    }
]

方案2生成的结果:

[
    "value1",
    "value2",
    "value3"
]

内容的提问来源于stack exchange,提问作者Creenis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:07:54