将Python中的文本文件解析为字典 [英] Parsing text file in Python into a dictionary
本文介绍了将Python中的文本文件解析为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个csv文件.我想根据这些数据创建字典.我不应该熊猫.数据如下:
I have a csv file. I want to create dictionary from this data.I should not pandas. Data looks like this:
我这样做.但是数字的大小不一样.如何创建字典?
I do this. But size of the numbers is not same. How can I create a dictionary?
filename=" data.dat"
file=open(filename, encoding="latin-1").read().split(' , ')
dictt={}
for row in file:
dictt[row[0]] = {‘values’, row[1]}
我有一个如上所述的文件.首先,我需要创建一个字典.之后,我将按照日期的降序打印每日唯一测量值的数量.
I have a file as above. First, I need to create a dict. After that, I will print the daily number of unique measurements in desending order according to date.
最终预期结果:
推荐答案
您好
随您便吧
with open("./test.txt") as myFile:
formattedData = dict()
for line in myFile:
try:
date , numbers = line.split(' , ')
numbers = numbers.replace("\n","")
numbers = numbers.split(',')
formattedData[date] = len(list(set(numbers)))
except:
date = line
formattedData[date] = 0
print(formattedData)
这篇关于将Python中的文本文件解析为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文