我有以下数据:
<http://dbpedia.org/data/Plasmodium_hegneri.xml> <http://code.google.com/p/ldspider/ns#headerInfo> _:header16125770191335188966549 <http://dbpedia.org/data/Plasmodium_hegneri.xml> .
_:header16125770191335188966549 <http://www.w3.org/2006/http#responseCode> "200"^^<http://www.w3.org/2001/XMLSchema#integer> <http://dbpedia.org/data/Plasmodium_hegneri.xml> .
_:header16125770191335188966549 <http://www.w3.org/2006/http#date> "Mon, 23 Apr 2012 13:49:27 GMT" <http://dbpedia.org/data/Plasmodium_hegneri.xml> .
_:header16125770191335188966549 <http://www.w3.org/2006/http#content-type> "application/rdf+xml; charset=UTF-8" <http://dbpedia.org/data/Plasmodium_hegneri.xml> .
现在我想将这些数据转换为以下形式 - 这样< >
中包含的最后一个字符串出现在它添加了#@的行之前。
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
<http://dbpedia.org/data/Plasmodium_hegneri.xml> <http://code.google.com/p/ldspider/ns#headerInfo> _:header16125770191335188966549 .
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
_:header16125770191335188966549 <http://www.w3.org/2006/http#responseCode> "200"^^<http://www.w3.org/2001/XMLSchema#integer> .
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
_:header16125770191335188966549 <http://www.w3.org/2006/http#date> "Mon, 23 Apr 2012 13:49:27 GMT" .
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
_:header16125770191335188966549 <http://www.w3.org/2006/http#content-type> "application/rdf+xml; charset=UTF-8" .
我写了下面的python代码,以便做同样的事情:
infile = open('testnq.nq', 'r')
outfile= open('outFile.ttl','w')
while True:
inFileLine1=infile.readline()
if not inFileLine1:
break #EOF
splitString=inFileLine1.split(' ')
line1= "#@ " + splitString[len(splitString)-2]
outfile.write(line1)
line2=""
for num in range (0,len(splitString)-2):
line2= line2 + splitString[num]
outFile.write(line2)
outFile.close()
但我无法获得所需位置的空间。有人可以建议我如何在python或使用linux命令
中做同样的事情答案 0 :(得分:1)
由于存在使用正则表达式和使事情复杂化的风险,这可能有效:
import re
line = """<http://dbpedia.org/data/Plasmodium_hegneri.xml> <http://code.google.com/p/ldspider/ns#headerInfo> _:header16125770191335188966549 <http://dbpedia.org/data/Plasmodium_hegneri.xml> ."""
print re.sub('^(?P<before>.*)(?P<match>\<[^>]+\>)(?P<after>[^<]*)$', '#@ \g<match>\n\g<before>\g<after>', line)
line = """_:header16125770191335188966549 <http://www.w3.org/2006/http#responseCode> "200"^^<http://www.w3.org/2001/XMLSchema#integer> <http://dbpedia.org/data/Plasmodium_hegneri.xml> ."""
print re.sub('^(?P<before>.*)(?P<match>\<[^>]+\>)(?P<after>[^<]*)$', '#@ \g<match>\n\g<before>\g<after>', line)
输出:
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
<http://dbpedia.org/data/Plasmodium_hegneri.xml> <http://code.google.com/p/ldspider/ns#headerInfo> _:header16125770191335188966549 .
#@ <http://dbpedia.org/data/Plasmodium_hegneri.xml>
_:header16125770191335188966549 <http://www.w3.org/2006/http#responseCode> "200"^^<http://www.w3.org/2001/XMLSchema#integer> .