【问题标题】:Python- how to convert .txt file (two columns) to dictionary elements?Python-如何将 .txt 文件(两列)转换为字典元素?
【发布时间】:2019-05-26 11:07:49
【问题描述】:

我想从 .txt 文件的两列中检查 x 和 y 的最小值和最大值,但我不知道如何。

大家好 :) 我进行了频谱分析,得到了超过 500 条频率线和相应的 dB。我想在 jupyter notebook 中创建一个字典,它可以让我检查 x 和 y 的最大值和最小值以及少数光谱分析的变化。我使用了这段代码:

y = {} 

with open('wow.txt', "r") as infile: 
    for line in infile: 
        key, value = line.strip().split(':') 
        y[key] = (value) 
print(y) 

还有

d = {}
with open('wow.txt') as f:
    for line in f:
        key, value = line.strip().split(':')
        d[key] = int(value)

但是有一个

ValueError : 没有足够的值来解包(预期 2,得到 1)。

我从程序中得到了这个值,并且有两列,那么我做错了什么?

【问题讨论】:

    标签: python file dictionary text key


    【解决方案1】:

    在文本文件的某处,没有':'字符,所以它不能分割行。也许某处有空行?

    另外,对于这类事情,我喜欢使用pandas,这是一个为此提供了一些有趣功能的库。

    import pandas as pd
    df = pd.read_csv(file, delimiter=':', names=['freq', 'db'])
    min = df.loc[df['db'].idxmin()]
    max = df.loc[df['db'].idxmax()]
    print('Minimum at {}Hz with a magnitude of {}dB'.format(min['freq'], min['db']))
    print('Maximum at {}Hz with a magnitude of {}dB'.format(max['freq'], max['db']))
    

    【讨论】:

    • 您的代码有效,谢谢 :) 但还有另一个问题。最小值不正确。我列表中的最小频率值为 43,066406 Hz,但程序在超过 10,000 Hz 的阈值后开始检查值。
    • 哦,对不起,如果你使用df.min(),它会分别获取每列的最小值。我会更新答案。
    • 但是从 df.min() 和 df.max() 返回的值很奇怪。一列用于频率,另一列用于 dB。程序将第一列分成两部分。例如,我将使用这个:[1, 2, 3, 4, 5, 6,] : [7, 8, 9, 10, 11, 12]。程序说最大是3:9,最小是4:10。而且这个新代码还有另一个错误:( TypeError: cannot do label indexing on with these indexers [nan] of
    • 如果您可以将您的数据文件(或部分,如果它非常长)上传到pastebin.com 或类似的东西并在此处分享链接,我可以采取进一步调查
    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2019-10-28
    • 2016-08-26
    • 2021-08-10
    相关资源
    最近更新 更多