我的文件f
类似于:
#labelA
there
is
something
here
#label_Bbb
here
aswell
...
一行上可以有多个标签和任意数量的元素(仅限str),每个标签可以有多行。 我想将这些数据存储在如下字典中:
d = {'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell', ...}
我有很多子问题:
答案 0 :(得分:7)
首先,header("Content-Type: text/html; charset=utf-8");
包含以#开头的键,值为列表( 列表可以将这些行保留为附加顺序 ),我们将行添加到此列表中,直到找到以#开头的下一行。然后我们只需要将行列表转换为一个单独的字符串。
我正在使用python3,如果你使用python2替换mydict
和mydict.items()
来迭代键值对
mydict.iteritems()
输出:
mydict = dict()
with open("sample.csv") as inputs:
for line in inputs:
if line.startswith("#"):
key = line.strip()[1:]
mydict.setdefault(key,list())
else:
mydict[key].append(line.strip())
result = dict()
for key, vlist in mydict.items():
result[key] = "".join(vlist)
print(result)
答案 1 :(得分:2)
使用re.findall()函数的最短解决方案:
import re
with open("lines.txt", 'r') as fh:
d = {k:v.replace('\n', '') for k,v in re.findall(r'^#(\w+)\s([^#]+)', fh.read(), re.M)}
print(d)
输出:
{'label_Bbb': 'hereaswell', 'labelA': 'thereissomethinghere'}
re.findall
将返回一个元组列表,每个元组包含两个代表两个连续捕获组的项目
答案 2 :(得分:2)
f = open('untitled.txt', 'r')
line = f.readline()
d = {}
last_key = None
last_element = ''
while line:
if line.startswith('#'):
if last_key:
d[last_key] = last_element
last_element = ''
last_key = line[:-1]
last_element = ''
else:
last_element += line
line = f.readline()
d[last_key] = last_element
答案 3 :(得分:1)
使用collections.defaultdict
:
from collections import defaultdict
d = defaultdict(list)
with open('f.txt') as file:
for line in file:
if line.startswith('#'):
key = line.lstrip('#').rstrip('\n')
else:
d[key].append(line.rstrip('\n'))
for key in d:
d[key] = ''.join(d[key])
答案 4 :(得分:1)
作为单一通行证而不制作临时词典:
res = {}
with open("sample") as lines:
try:
line = lines.next()
while True:
entry = ""
if line.startswith("#"):
next = lines.next()
while not next.startswith("#"):
entry += next
next = lines.next()
res[line[1:]] = entry
line = next
except StopIteration:
res[line[1:]] = entry # Catch the last entry
答案 5 :(得分:1)
我会做这样的事情(这是伪代码所以它不会编译!)
dict = dict()
key = read_line()[1:]
while not end_file():
text = ""
line = read_line()
while(line[0] != "#" and not end_file()):
text += line
line = read_line()
dict[key] = text
key = line[1:]
答案 6 :(得分:1)
这是我的方法:
def eachChunk(stream):
key = None
for line in stream:
if line.startswith('#'):
line = line.rstrip('\n')
if key:
yield key, value
key = line[1:]
value = ''
else:
value += line
yield key, value
您可以像这样快速创建所希望的词典:
with open('f') as data:
d = dict(eachChunk(data))