Kei*_*haw 9 python parsing python-2.7 turtle-rdf
我有一个.ttl表格的文件.它有4个属性/列,包含以下形式的四元组:
(id, student_name, student_address, student_phoneno). (id, faculty_name, faculty_address, faculty_phoneno).我知道如何.n3使用RDFLib 解析表格三元组;
from rdflib import Graph
g = Graph()
g.parse("demo.nt", format="nt")
Run Code Online (Sandbox Code Playgroud)
但我不确定如何解析这些四倍.
我的目的是解析和提取与特定id有关的所有信息.学生和教师的身份证可以相同.
如何使用RDFLib处理这些四元组并将其用于聚合id?
.ttl文件中的示例代码段:
#@ <id1>
<Alice> <USA> <12345>
#@ <id1>
<Jane> <France> <78900>
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 10
Turtle是Notation 3语法的子集,因此rdflib应该能够使用它来解析它format='n3'.检查是否rdflib保留注释(在样本id的comments(#...)中指定了注释).如果没有,输入格式就像示例中所示的那样简单,那么您可以手动解析它:
import re
from collections import namedtuple
from itertools import takewhile
Entry = namedtuple('Entry', 'id name address phone')
def get_entries(path):
with open(path) as file:
# an entry starts with `#@` line and ends with a blank line
for line in file:
if line.startswith('#@'):
buf = [line]
buf.extend(takewhile(str.strip, file)) # read until blank line
yield Entry(*re.findall(r'<([^>]+)>', ''.join(buf)))
print("\n".join(map(str, get_entries('example.ttl'))))
Run Code Online (Sandbox Code Playgroud)
输出:
Entry(id='id1', name='Alice', address='USA', phone='12345')
Entry(id='id1', name='Jane', address='France', phone='78900')
Run Code Online (Sandbox Code Playgroud)
要将条目保存到数据库:
import sqlite3
with sqlite3.connect('example.db') as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS entries
(id text, name text, address text, phone text)''')
conn.executemany('INSERT INTO entries VALUES (?,?,?,?)',
get_entries('example.ttl'))
Run Code Online (Sandbox Code Playgroud)
如果需要在Python中进行一些后处理,则按ID分组:
import sqlite3
from itertools import groupby
from operator import itemgetter
with sqlite3.connect('example.db') as c:
rows = c.execute('SELECT * FROM entries ORDER BY id LIMIT ?', (10,))
for id, group in groupby(rows, key=itemgetter(0)):
print("%s:\n\t%s" % (id, "\n\t".join(map(str, group))))
Run Code Online (Sandbox Code Playgroud)
输出:
id1:
('id1', 'Alice', 'USA', '12345')
('id1', 'Jane', 'France', '78900')
Run Code Online (Sandbox Code Playgroud)
看起来至少从 rdflib 5.0.0 开始支持turtle。我做到了
from rdflib import Graph
graph = Graph()
graph.parse('myfile.ttl', format='ttl')
Run Code Online (Sandbox Code Playgroud)
这解析得很好。
Abh*_*jit -2
目前似乎没有这样的库来解析Turtle - 简洁的 RDF 三重语言
由于您已经了解语法,因此最好的选择是使用PyParsing首先创建语法,然后解析文件。
我还建议根据您的需要调整以下EBNF 实现
| 归档时间: |
|
| 查看次数: |
10177 次 |
| 最近记录: |