如何在字典键值对的双引号与冒号之间添加空格?
解决JSON键值对双引号与冒号间添加空格的问题
问题说明
需要将字典转换为字符串时,在键的双引号与冒号之间添加空格,使输出格式从{"John": 2}变为{"John" : 2}。
原代码
import json def value_list(sentence): word_list = sentence.split(" ") total_number_of_words_in_the_sentence = len(word_list) value_list = [] for i in range(0, total_number_of_words_in_the_sentence): count1 = word_list.count(word_list[i]) value_list.append(count1) return value_list def wordlist1(sentence): import json word_list = sentence.split() total_number_of_words_in_the_sentence = len(word_list) for i in range(0,total_number_of_words_in_the_sentence): word_list[i] = word_list[i] return word_list def word_frequency1(sentence): dict1 = dict(zip(wordlist1(sentence), value_list(sentence))) dict2 = json.dumps(dict1) return dict2 print(word_frequency1("John is a businessman and John is a programmer."))
当前输出
{"John": 2, "is": 2, "a": 2, "businessman": 1, "and": 1, "programmer.": 1}
期望输出
{"John" : 2, "is" : 2, "a" : 2, "businessman" : 1, "and" : 1, "programmer." : 1}
解决方案
json.dumps()遵循标准JSON格式,不会在双引号和冒号之间添加空格,因此需要手动构建目标格式的字符串:
- 使用
collections.Counter可以更简洁地统计词频,替代原有的两个冗余函数; - 将每个键值对格式化为
"键" : 值的字符串; - 拼接所有键值对并包裹大括号,得到最终格式。
修改后的代码:
from collections import Counter def word_frequency1(sentence): # 分割句子并统计词频 word_counts = Counter(sentence.split()) # 格式化每个键值对为指定格式 items = [f'"{key}" : {value}' for key, value in word_counts.items()] # 拼接成最终字符串 return '{' + ', '.join(items) + '}' print(word_frequency1("John is a businessman and John is a programmer."))
代码说明
Counter(sentence.split()):自动分割句子并统计每个单词的出现次数,比原代码的循环统计更高效;f'"{key}" : {value}':将每个键值对格式化为带空格的目标样式;', '.join(items):把所有格式化后的键值对用,连接,再包裹大括号,得到符合要求的字符串。
内容的提问来源于stack exchange,提问作者Farhan
相关产品推荐
相关产品推荐

