使用 txt 文件作为输入创建 RDF 文件

发布于 2024-12-28 18:48:03 字数 74 浏览 2 评论 0原文

如何使用 python 模块 RDFlib 将简单的制表符分隔 txt 文件(包含标头主语、谓语、宾语)转换为 RDF N-三重格式?

How can I convert a simple tab-delimited txt file (containing the headers subject, predicate, object) into a RDF N-triple format using the python module RDFlib?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最佳男配角 2025-01-04 18:48:03

这不是很复杂。首先,一些必要的导入:

from StringIO import StringIO
from rdflib import Graph, URIRef

我在这里使用 StringIO 以避免创建文件。相反,我将只列出一些内容和一个包含这些内容的类似文件的对象:

contents = '''\
subject1\tpredicate1\tobject1
subject2\tpredicate2\tobject2'''  
tabfile = StringIO(contents)

然后创建一个图表并将所有三元组加载到其中:

graph = rdflib.Graph()

for line in tabfile:
    triple = line.split()                # triple is now a list of 3 strings
    triple = (URIRef(t) for t in triple) # we have to wrap them in URIRef
    graph.add(triple)                    # and add to the graph

现在您在内存中拥有整个图表(当然假设您有足够的内存)。您现在可以打印它:

print graph.serialize(format='nt')

# prints:
# <subject1> <predicate1> <object1> .
# <subject2> <predicate2> <object2> .

It's not very complicated. First, some necessary imports:

from StringIO import StringIO
from rdflib import Graph, URIRef

I'm using StringIO here to avoid creating a file. Instead, I'll just list some contents and a file-like object with these contents:

contents = '''\
subject1\tpredicate1\tobject1
subject2\tpredicate2\tobject2'''  
tabfile = StringIO(contents)

Then create a graph and load all triples to it:

graph = rdflib.Graph()

for line in tabfile:
    triple = line.split()                # triple is now a list of 3 strings
    triple = (URIRef(t) for t in triple) # we have to wrap them in URIRef
    graph.add(triple)                    # and add to the graph

Now you have the whole graph in memory (assuming you have enough memory, of course). You can now print it:

print graph.serialize(format='nt')

# prints:
# <subject1> <predicate1> <object1> .
# <subject2> <predicate2> <object2> .
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文