簡體   English   中英

Python-如何將.txt文件(兩列)轉換為字典元素?

[英]Python- how to convert .txt file (two columns) to dictionary elements?

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

大家好:)我進行了頻譜分析,得到了500多條頻率線和相應的dB。 我想在jupyter筆記本中創建一個字典,使我可以檢查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)。

我從程序中獲得了此值,並且有兩列,所以我做錯了什么?

文本文件中的某處沒有':'字符,因此它不能分割行。 也許某處空行?

另外,對於這種事情,我喜歡使用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']))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM