[英]How to convert this text file into a dictionary?
我有一個文件f
看起來像:
#labelA
there
is
something
here
#label_Bbb
here
aswell
...
它可以在一行上有許多標簽和任意數量的元素(僅限str),每行標簽可以有多行。 我想將這些數據存儲在如下字典中:
d = {'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell', ...}
我有一些子問題:
首先, mydict
包含以#開頭的鍵,值是一個列表( 列表可以將行保持在它們的附加順序中 ),我們將行添加到此列表中,直到我們找到以#開頭的下一行。 然后我們只需要將行列表轉換為一個單獨的字符串。
我正在使用python3,如果你使用python2替換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)
輸出:
{'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell'}
使用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
將返回元組列表,每個元組包含兩個表示兩個連續捕獲組的項
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
使用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])
作為單一通行證而不制作臨時詞典:
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
我會做這樣的事情(這是偽代碼所以它不會編譯!)
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:]
這是我的方法:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.