我试图把字符串集合,记号化字符串 成单个字符,并重组他们到JSON用于 构建聚类图可视化的目的(有点像this word tree,除了字符串而不是句子)。因此,有时候字符序列会在数据之间共享(或重新共享)。构建的纯文本JSON
因此,举例来说,可以说我有一个文本文件,它看起来像:
xin_qn2
x_qing4n3
x_qing4nian_
这是我期待我的输入;没有CSV标题或与数据相关的任何内容。 JSON对象,然后将看起来像:
{
"name": "x",
"children": [
{
"name": i,
},
{
"name": _,
"children": [
{
"name": "q"
}
]
}
]
}
等。在将数据发送到D3.js之前,我一直在尝试构造数据,使用Ruby将行分割成单独的字符,但是我一直试图弄清楚如何在层次结构JSON中构造这些数据。
file_contents = File.open("single.txt", "r")
file_contents.readlines.each do |line|
parse = line.scan(/[A-Za-z][^A-Za-z]*/)
puts parse
end
我可以在浏览器中用d3.js代替,我只是还没有尝试过。
只是想知道是否有任何建议,指针或现有的工具/脚本,可能会帮助我。谢谢!
更新2014年10月2日
所以我花了一点时间在Python尝试这一点,但我一直卡住。我现在看到,我也不正确地处理“儿童”元素。有什么建议么?
尝试一个
#!/usr/bin/python
from collections import defaultdict
import json
def tree():
return defaultdict(tree)
file_out = open('out.txt', 'wb')
nested = defaultdict(tree)
with open("single.txt") as f:
for line in f:
o = list(line)
char_lst = []
for chars in o:
d = {}
d['name']=chars
char_lst.append(d)
for word in d:
node = nested
for char in word:
node = node[char.lower()]
print node
print(json.dumps(nested))
尝试两个
#!/usr/bin/python
from collections import defaultdict
import json
def tree():
return defaultdict(tree)
nested = defaultdict(tree)
words = list(open("single.txt"))
words_output = open("out.json", "wb")
for word in words:
node = nested
for char in word:
node = node[char.lower()]
def print_nested(d, indent=0):
for k, v in d.iteritems():
print '{}{!r}:'.format(indent * ' ', k)
print_nested(v, indent + 1)
print_nested(nested)
您需要制作一堆字典,然后将它们存储在列表中。我不能说Ruby,但是Python使这非常简单。 – 2014-09-28 22:57:32