python - 如何从数据集中删除无用元素

标签 python json preprocessor

我有一个数据集,它如下所示:

 {0: {"address": 0,
         "ctag": "TOP",
         "deps": defaultdict(<class "list">, {"ROOT": [6, 51]}),
         "feats": "",
         "head": "",
         "lemma": "",
         "rel": "",
         "tag": "TOP",
         "word": ""},
     1: {"address": 1,
         "ctag": "Ne",
         "deps": defaultdict(<class "list">, {"NPOSTMOD": [2]}),
         "feats": "_",
         "head": 6,
         "lemma": "اشرف",
         "rel": "SBJ",
         "tag": "Ne",
         "word": "اشرف"},

我想从此数据集中删除 "deps":...?。我尝试了这段代码,但不起作用,因为 "depts": 的值在字典的每个元素中都不同。

import re
import simplejson as simplejson

with open("../data/cleaned.txt", 'r') as fp:
    lines = fp.readlines()
    k = str(lines)
    a = re.sub(r'\d:', '', k) # this is for removing numbers like `1:{..`
    json_data = simplejson.dumps(a)
    #print(json_data)
    n = eval(k.replace('defaultdict(<class "list">', 'list'))
    print(n)

最佳答案

正确的方法是修复生成文本文件的代码。这个defaultdict(<class "list">, {"ROOT": [6, 51]})暗示它使用了一个简单的 repr当需要更智能的格式时。

如果无法进行真正的修复,以下只是一个穷人的解决方法。

摆脱"deps": ...很简单:一次读取文件一行并丢弃以 ""deps" 开头的任何一行就足够了。 (忽略最初的空格)。但这还不够,因为当 json 坚持键只是文本时,文件包含数字键。因此必须识别并引用数字键。

这可以允许加载文件:

重新导入 将 simplejson 导入为 simplejson

with open("../data/cleaned.txt", 'r') as fp:
    k = ''.join(re.sub(r'(?<!\w)(\d+)', r'"\1"',line)
        for line in fp if not line.strip().startswith('"deps"'))

# remove an eventual last comma
k = re.sub(r',[\s\n]*$', '', k, re.DOTALL)

# uncomment if the file does not contain the last }
# k += '}'

js = json.loads(k)

关于python - 如何从数据集中删除无用元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55042037/

相关文章:

python - 使用 df1 中的值从 df2 中检索值,其中 df2 列和索引包含一系列值

java - Moshi 有像 Gson 这样的运行时类型适配器工厂吗?

php - Drupal *_preprocess 模块

ios - 解析 JSON 帮助 IOS

javascript - 在 Karma/Mocha 中加载 Json fixture

c++ - 如何将 CGO 用于具有条件内联函数的头文件?

c++ - #ifdef VALUE 与 #if Defined (VALUE) 之间有什么区别

Python 重置列中间隔内的累积和

python - 从 CMD 运行带有额外内容的 Python 文件

python - 在python中检测像素化图像