我有一个文本,我想将其转换为字典。
以下是文字的格式:
dic_text = {'apple-0-orange-5-text1' : 'random text','apple-0-orange-5-text2' : 'random text','apple-0-orange-5-text3' : 'random text','apple-0-orange-5-text4' : 'random text','apple-0-orange-6-text1' : 'random text','apple-0-orange-6-text2' : 'random text','apple-0-orange-6-text3' : 'random text','apple-0-orange-6-text4' : 'random text','apple-1-orange-12-text1' : 'random text','apple-1-orange-12-text2' : 'random text','apple-1-orange-12-text3' : 'random text','apple-1-orange-12-text4' : 'random text','apple-1-orange-13-text1' : 'random text','apple-1-orange-13-text2' : 'random text','apple-1-orange-13-text3' : 'random text','apple-1-orange-13-text4' : 'random text'}
我想将字典转换成这样:
def KMV(x, *args):
valueToEquity = float(x[0])
volOfValue = float(x[1])
equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity = args
d1 = (np.log(equityToDebt * equityToDebt) + (riskFreeRate + 0.5 * volOfEquity**0.5)
* TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
d2 = (np.log(abs(equityToDebt * equityToDebt)) + (riskFreeRate - 0.5 * volOfEquity**0.5)
* TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
f1 = valueToEquity * norm.cdf(d1) - np.exp(-riskFreeRate * TimeToMaturity) * norm.cdf(d2) / equityToDebt - 1
f2 = norm.cdf(d1) * valueToEquity * volOfValue - volOfEquity
return f1, f2
def solver():
equityToDebt = 1
volOfEquity = 0.2
riskFreeRate = 0.03
TimeToMaturity = 1
args = equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity
x0 = [1, 0.2]
sol = fsolve(KMV, x0, args=args)
print(sol)
有谁能告诉我制作字典的通用方法吗?
答案 0 :(得分:1)
假设您未提供以下信息(请编辑澄清是否成立的问题):
random text
不跨越多行)random text
random text
不能只是空白:
:
结尾的行(加上最终的空格),因此random text
不能以:
结尾。然后你可以这样做:
def build_dict(iterable):
result = {}
main_key = None
sub_key = None
for line in iterable:
# remove whitespace at beginning/end of line
line = line.strip()
if not line:
# throw away empty lines
continue
elif ':' not in line:
# we found an "Apple X" line, transform that into apple-X
main_key = '-'.join(line.lower().split())
sub_key = None
elif line[-1] == ':':
# we found an "orange X" line
sub_key = '-'.join(line.lower().split())
else:
# add a `textX : random_text` element
key, value = line.split(':')
result['-'.join([main_key, sub_key, key.strip()])] = value.strip()
return result
因此,您要跟踪Apple X
中的main_key
值,以及orange Y
中的sub_key
值以及之后的所有行text X : random_text
在:
上拆分并合并三个键,并将值保存在字典中。
如果我所做的假设不成立,那么你必须处理多行值等事情,这完全取决于文件的格式。