python 提取特定字符所在的行,并构建字典

如题,数据类型为:>xxxxxxxx xxx xxxx
yyyyyyyyyyyyyyyy
yyyyyyyyyyyyyy

>xxxxxxxx xxxx xxxxxx
yyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyy
这样的格式,每个项的第一行都是>开头的,能不能以这个作为信息,提取它所在的第一行标题作为一个字典的key,紧接着的后几行作为对应的value,这样构建一个字典
最终得到的key应该为完整的数据中的第一行,包括那个大于号(>);
每项间最好有一个空行;
字典保存为另一个文件比较好,不要直接输出在屏幕上

import re
testfile=open(r"test.txt")
teststr=testfile.read()
teststr+="\n>"
testdict={}
reg=re.compile(r"^\s*>(.+?)$(.+?)(?=(^\s*>))",re.M+re.S)
matchs=reg.finditer(teststr)

for match in matchs:
    key=match.group(1)
    value=match.group(2)
    testdict[key]=value

print testdict

以上代码假设数据是存储在文件test.txt中的,最后打印出来的字典 testdict 符合要求吧


追问

你的答案很接近了,但是每行的大于号都变成了逗号怎么回事?每项的结尾都多了"\n".
能不能解释下重要步骤的含义啊,新手菜鸟,请多指教

追答import re
import anydbm
testfile=open(r"test.txt")
teststr=testfile.read()
teststr+="\n>"
reg=re.compile(r"^\s*(>.+?)$(.+?)(?=(^\s*>))",re.M+re.S)
matchs=reg.finditer(teststr)
testdb=anydbm.open(r"test.dict",'n')
for match in matchs:
    key=match.group(1)
    value=match.group(2)
    testdb[key]=value.strip('\n')
testdb.close()
testdb=anydbm.open(r"test.dict",'r')
for key in  testdb.keys():
    print "key:",key
    print "value:",testdb[key]
    print '\n'
testdb.close()

 上面有行号,按行号解释一下,

5行:在文本最后加上一行使文本以换行加>号结束,使最后的一对key,value能够正确匹配

6行:正则表达式对象,匹配文本中要提取的key,value对。

7行:matchs=reg.finditer(teststr)提取文本中每个匹配的key,value对

9-12循环迭代每个匹配的文本,将key,value写入字典文件

15-18行重新打开文件,测试文件写入是否正确

anydbm是python中一个简单数据库文件对象,可以将字典写入文件

上面是python2的代码,如果是python3将anydbm改为dbm,print语句加圆括号即可

追问

基本可以了,就是还没有把生成的字典单独作为一个文件输出,不显示在屏幕上,因为生成这个字典肯定是后面要用的,是吧。
再问一下,如果后面想引用这个字典的话,就是用它的key,怎么表示呢?

追答

第8行:testdb=anydbm.open(r"test.dict",'n')已经打开一个名为"test.dict"的文件保存字典了
以后可以用python程序读出来,第14-19行就是读这个文件的代码。
import anydbm
testdb=anydbm.open(r"test.dict",'r')
for key in testdb.keys():
print "key:",key
print "value:",testdb[key]
print '\n'
testdb.close()

这几行代码可以不要,然后单独保存为一个程序读取字典,和普通字典用法差不多

追问

这几行代码不要的话就会显示
testdb[key]=value.strip('\n')
NameError: name 'testdb' is not defined
我是想问,能不能修改下程序,直接程序运行的结果就是生成一个字典文件,以便后面能用,而不是像这样输出在屏幕上,再导出到文件。

追答import re
import anydbm
testfile=open(r"test.txt")
teststr=testfile.read()
teststr+="\n>"
reg=re.compile(r"^\s*(>.+?)$(.+?)(?=(^\s*>))",re.M+re.S)
matchs=reg.finditer(teststr)
testdb=anydbm.open(r"testdict",'n')
for match in matchs:
    key=match.group(1)
    value=match.group(2)
    testdb[key]=value.strip('\n')
testdb.close()

这几行代码不要没有任何问题,而且已经生成了一个名为“testdict”的字典文件,应该就和代码在同一文件夹。

读取这个testdict文件的代码上面已经给出

受不了了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-22
class SCollector:
def __init__(self):
self.dict = {}
self.title = None
def append(self, line):
if line.startswith('>'):

self.title = line.strip()[1:]
self.dict[self.title] = []
else:
self.dict[self.title].append(line.strip())
def items(self):
for k, v in self.dict.items():
yield k, v

scollector = SCollector()
with open(thetextfile, 'rt') as handle:
map(scollector.append, handle)

import pprint
pprint.pprint(scollector.dict)追问

Traceback (most recent call last):
File "02.py", line 18, in map(scollector.append, handle)
File "02.py", line 11, in append self.dict[self.title].append(line.strip())
KeyError: None

追答

def append(self, line):
if line.startswith('>'):
self.title = line.strip()[1:]
self.dict[self.title] = []
else:
self.dict.setdefault(self.title, []).append(line.strip())

追问

脚本命名为02.py,运行结果如下
File "02.py", line 5
def append(self, line):
^
IndentationError: unindent does not match any outer indentation level
还是有错误啊,你可以再看下我的题目,又补充的详细了点

相似回答