我需要python编写代码的帮助,我需要编写一段代码,用单词在句子中的位置/索引创建一个json或xml,无论单词中的所有字符是否都是字母,最后是它们提供给我的句子中每个单词的单词本身。我首先考虑使用一个简单的字典来存储键值,然后将字典转换为json:
import json
data = {}
liste = [] # it's for storing all the words after splitting them by space
sentence="As its price tag has been slashed to $1.7trn over a decade, half as much as first pitched, the hungerâor squidâgames between progressives and moderates have turned fiercer."
liste = sentence.split(" ")
for word,index in zip(liste,range(0,len(liste))):
data[word.lower()] = {"alpha":word.lower().isalpha()}
data[word.lower()]['Word'] = word.lower()
data[word.lower()]['Index'] = index
json_data = json.dumps(data,ensure_ascii=False)
print(json_data)
它打印出这个json:
{"as": {"alpha": true, "Word": "as", "Number": 15}, "its": {"alpha": true, "Word": "its", "Number": 1}, "price": {"alpha": true, "Word": "price", "Number": 2}, "tag": {"alpha": true, "Word": "tag", "Number": 3}, "has": {"alpha": true, "Word": "has", "Number": 4}, "been": {"alpha": true, "Word": "been", "Number": 5}, "slashed": {"alpha": true, "Word": "slashed", "Number": 6}, "to": {"alpha": true, "Word": "to", "Number": 7}, "$1.7trn": {"alpha": false, "Word": "$1.7trn", "Number": 8}, "over": {"alpha": true, "Word": "over", "Number": 9}, "a": {"alpha": true, "Word": "a", "Number": 10}, "decade,": {"alpha": false, "Word": "decade,", "Number": 11}, "half": {"alpha": true, "Word": "half", "Number": 12}, "much": {"alpha": true, "Word": "much", "Number":14}, "first": {"alpha": true, "Word": "first", "Number": 16}, "pitched,": {"alpha": false, "Word": "pitched,", "Number": 17}, "the": {"alpha": true, "Word": "the", "Number": 18}, "hungerâor": {"alpha": false, "Word": "hungerâor", "Number": 19}, "squidâgames": {"alpha": false, "Word": "squidâgames", "Number": 20}, "between": {"alpha": true, "Word": "between", "Number": 21}, "progressives": {"alpha": true, "Word": "progressives", "Number": 22}, "and": {"alpha": true, "Word": "and", "Number": 23}, "moderates": {"alpha": true, "Word": "moderates", "Number": 24}, "have": {"alpha": true, "Word": "have", "Number": 25}, "turned": {"alpha": true, "Word": "turned", "Number": 26}, "fiercer.": {"alpha": false, "Word": "fiercer.", "Number": 27}}
正如你所看到的,这个json是不正确的,缺少了一些单词(另外两个“As”)。在对stackoverflow做了一些研究后,我想我开始明白为什么了:如果我的理解是正确的,字典和json对象不能多次具有相同的键。但问题是,在大多数英语句子中,有些单词是重复的。
一个英语句子的例子:随着它的价格在十年内被削减到1.7万亿美元,是最初报价的一半,进步派和温和派之间更激烈的争吵变得更加激烈。
在这个句子中,“as”这个词重复了3次,所以我认为在我的代码中,字典中的键被覆盖了两次,因为有3个单词“as”。我的想法正确吗?如果是对的,我能做些什么来解决这个问题?我可以绕过字典或json问题的唯一键吗?我应该使用哪种数据结构,如何获得json或xml作为输出?