【问题标题】:lowercase all the letters in json小写json中的所有字母
【发布时间】:2021-11-10 15:08:24
【问题描述】:

我的 json 文件看起来像这样-

{"classes":["BUSINESS","PLACE","HOLD","ROAD","SUB","SUPER","EA","DIS","SUB","UNI"],"annotations":[["Khilg Khil Block A Dha M K Enter House 308/A Road 8 Til Rhy", {"entities": [[0, 8, "EA"], [9, 17, "SUB"], [18, 25, "SUPER"], [26, 31, "DIS"], [32, 46, "BUSINESS"], [47, 58, "HOLDING"], [59, 65, "ROAD"], [66, 75, "SUB"], [76, 82, "PLACE"]]}]

在这种情况下,我想让每个字母都小写,以获得完整的文件。但它不起作用。 我的代码-

data = json.load(open("data.json"))
new_data = {}

for i in new_data.keys():
    if type(new_data[i]) is list:
        new_data[i]=  [j.lower() for j in new_data[i]]
    else:
        new_data[i] = new_data[i].lower()

with open("data.json", 'w') as fp:
    json.dump(new_data, fp)

【问题讨论】:

  • 你有什么问题?
  • 您可能只想将整个文件作为字符串读取,将其转换为小写,然后对结果字符串进行 JSON 解析和/或将其写回文件。

标签: python pandas dataframe dictionary lowercase


【解决方案1】:

由于您的数据中有列表列表,我认为最好使用递归。

代码:

def recursion_lower(x):
    if type(x) is str:
        return x.lower()
    elif type(x) is list:
        return [recursion_lower(i) for i in x]
    elif type(x) is dict:
        return {recursion_lower(k):recursion_lower(v) for k,v in x.items()}
    else:
        return x

data = {'classes': ['BUSINESS', 'PLACE', 'HOLD', 'ROAD', 'SUB', 'SUPER', 'EA', 'DIS', 'SUB', 'UNI'], 'annotations': [['Khilg Khil Block A Dha M K Enter House 308/A Road 8 Til Rhy', {'entities': [[0, 8, 'EA'], [9, 17, 'SUB'], [18, 25, 'SUPER'], [26, 31, 'DIS'], [32, 46, 'BUSINESS'], [47, 58, 'HOLDING'], [59, 65, 'ROAD'], [66, 75, 'SUB'], [76, 82, 'PLACE']]}]]}

new_data = recursion_lower(data)
print(new_data)

输出:

{'classes': ['business', 'place', 'hold', 'road', 'sub', 'super', 'ea', 'dis', 'sub', 'uni'], 'annotations': [['khilg khil block a dha m k enter house 308/a road 8 til rhy', {'entities': [[0, 8, 'ea'], [9, 17, 'sub'], [18, 25, 'super'], [26, 31, 'dis'], [32, 46, 'business'], [47, 58, 'holding'], [59, 65, 'road'], [66, 75, 'sub'], [76, 82, 'place']]}]]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2017-08-26
    • 1970-01-01
    • 2011-01-16
    • 2011-06-01
    • 1970-01-01
    • 2019-08-28
    • 2019-08-23
    相关资源
    最近更新 更多