首页 > 解决方案 > 使用 python 从文件中创建和使用字典

问题描述

对python很陌生,并试图完成一个有助于工作的项目。

我正在使用具有 3 列数据的 csv 文档,我希望 python 进入文件对 ssc 进行排序并将相关的 tprs(因为其中一些将有 2 个 tprs)与每个 ssc 的费率相匹配。它看起来像这样。

ssc,tpr,rate    
0149,01394,OffPeak    
0150,00042,Day    
0150,00207,Night    
0151,00043,Day    
0151,00210,OffPeak    
0152,00045,Day    
0152,00211,Night    
0153,00046,Day    

我的程序的一部分将在请求输入 ssc 以确保它存在之后搜索此文档,然后我希望它抓取它ssctpr并在单独的字典列表或 w/e 中评价和使用它们,以便我可以使用它们来填写我程序的其他部分。

我的第一个问题是希望只是浏览文件并对所有内容进行排序,因为我宁愿拥有一个 ssc tpr1 + ratetpr2 + rate例如

ssc  tpr1  rate  tpr2  rate    
0151 00043 Day  00210 Offpeak

或者如果只有一个 tpr 和 rate

ssc   tpr1  rate    
0393  00001 UnrestrictedSingle

然后我需要 python 通过添加额外的行来调整程序的另一部分,具体取决于有多少 tprs。所以如果只有 1 则只需添加 1 但如果有 4 则需要为 tprs 添加 4 行

看起来像

ZPI||    
ZIN||||||    
ISD||    
EAH||    
EAD|tpr1||    
EAD|tpr2||    
REG|||    
PSC||countofrates|ssc|    
IMC|||    
GSP|||    
IES|||    
ZPT|||||

以EAD开头的行是需要添加的行,具体取决于tprs有多少,countofrates需要根据有1个或2个来更改

对此的任何帮助将不胜感激!如果需要,很乐意分享任何额外的东西

谢谢!

ps

到目前为止,这就是我所拥有的一切仍以简单的形式,因为我无法使用我的文件来填写我也想要的部分。

fname = open('tprsheettidy.txt')
SSClist = list()              
for line in fname:  
    num = line.split()
    ssc = num  
    for ssc in num:
        if ssc in SSClist : continue                             
    SSC = num[0] 
    SSClist.append(SSC)  
 




print("""What flow would you like to make? D0019 and D0086""")

Dflow = input("> ")
prompt = '> '




if Dflow == "D0019 and D0086":
    print("please enter the SSC")
    SSC = input ("> ")
    if SSC in SSClist:
        print(SSC,"is a valid SSC")

        if SSC == "0393":
            print(f"What is the current time and date?")
            TAD = input(prompt)
            print(f"What is the MPAN?")
            MPAN = input(prompt)
            print(f"What is the supply start date")
            REGI = input(prompt)
            print(f"What is the EAC?")
            EAC = input(prompt)
            print(f"Please enter the GPS code")
            GSP = input(prompt)
            print(f"What is the Meter Serial Number?")
            MSN = input(prompt)
            print(f"Please enter 'c' for customer read or 'd' for an estimated read")
            READTYPE = input(prompt)
            print(f"What is the REG ID?")
            REGID1 = input(prompt)
            print(f"Please enter the meter reading")
            METERREADING1 = input(prompt)
            print(f"""ZHV|000000|D0119001|X|PSUK|D|LBSL|{TAD}||||OPER|
ZPI|652|   
ZIN|47862|NH09|{MPAN}|||
ISD|{REGI}|
EAH|{REGI}| 
EAD|00001|{EAC}|
REG|{REGI}|PSUK|
PSC|20170727|1|0393|
IMC|20200507|A|
GSP|19960401|{GSP}|
IES|20200507|E|
ZPT|000000|10|1|{TAD}|

ZHV|000000|D0086002|X||D||{TAD}||||OPER|
196|{MPAN}|V|
197|{MSN}|{READTYPE}|
198|{REGID1}|{REGI}000000|{METERREADING1}||T|N|
ZPT|000000|3||1|{TAD}|
""")
        elif SSC == "0151":
            print(f"What is the current time and date?")
            TAD = input(prompt)
            print(f"What is the MPAN?")
            MPAN = input(prompt)
            print(f"What is the supply start date")
            REGI = input(prompt)
            print(f"What is the EAC?")
            EAC = input(prompt)
            EACDAY = (0.66 * float(EAC))
            EACNIGHT = (0.33 * float(EAC))
            print(f"Please enter the GPS code")
            GSP = input(prompt)
            print(f"What is the Meter Serial Number?")
            MSN = input(prompt)
            print(f"Please enter 'c' for customer read or 'd' for an estimated read")
            READTYPE = input(prompt)
            print(f"What is the first REG ID?")
            REGID1 = input(prompt)
            print(f"What is the second REG ID?")
            REGID2 = input(prompt)
            print(f"Please enter the meter reading for REGID {REGID1}")
            METERREADING1 = input(prompt)
            print(f"Please enter the meter reading for REGID {REGID2}")
            METERREADING2 = input(prompt)
            print(f"""ZHV|000000|D0119001|X|PSUK|D|LBSL|{TAD}||||OPER|
ZPI|652|   
ZIN|47862|NH09|{MPAN}|||
ISD|{REGI}|
EAH|{REGI}| 
EAD|00043|{EACDAY}|
EAD|00210|{EACNIGHT}|
REG|{REGI}||
PSC|20170727|1|0393|
IMC|20200507|A|
GSP|19960401|{GSP}|
IES|20200507|E|
ZPT|000000|10|1|{TAD}|

ZHV|000000|D0086002|X||D||{TAD}||||OPER|
196|{MPAN}|V|
197|{MSN}|{READTYPE}|
198|{REGID1}|{REGI}000000|{METERREADING1}||T|N|
198|{REGID2}|{REGI}000000|{METERREADING2}||T|N|
ZPT|000000|3||1|{TAD}|
""")

这仅适用于两个特定的 ssc,即 0393 和 0151,但由于文件中有更多内容,我希望能够将它们填充到该程序中。

再次感谢

标签: python

解决方案


您可以使用pandas轻松地从 CSV 文件创建字典。


In [1]: import pandas as pd

In [2]: mydata = pd.read_csv('mydata.csv', dtype=str)

In [3]: myssc = mydata.loc[mydata['ssc'] == '0151', :]

In [4]: print(f'Number of tprs: {myssc.shape[0]}')
Number of tprs: 2

In [6]: mydict = myssc.loc[:, ['tpr', 'rate']].to_dict()

In [7]: mydict
Out[7]: {'tpr': {3: '00043', 4: '00210'}, 'rate': {3: 'Day', 4: 'OffPeak'}}

In [8]: mydict = myssc.loc[:, ['tpr', 'rate']].to_dict('records')

In [9]: mydict
Out[9]: [{'tpr': '00043', 'rate': 'Day'}, {'tpr': '00210', 'rate': 'OffPeak'}]

pandas.DataFrame.to_dict()方法有许多选项可以根据您的需要以不同的方式布置 dicts。


推荐阅读