【问题标题】:changing comma in csv to semicolon将csv中的逗号更改为分号
【发布时间】:2020-09-26 20:35:45
【问题描述】:

('径向速度', {'数字': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 5.0 , 5.0, 5.0, 5.0, 5.0, 3.0, 3.0, 3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 1.0 , 1.0, 1.0, 1.0, 4.0, 4.0, 4.0, 4.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 2.0, 1.0, 3.0, 3.0, 3.0 , 1.0, 2.0, 2.0, 1.0, 1.0, 1.0, 4.0, 4.0, 4.0, 4.0, 1.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 1.0, 3.0, 3.0, 3.0, 1.0, 1.0, 4.0, 4.0 , 4.0, 4.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 'orbital_period':

这是我的代码示例输出:

def parse_planets_file(file):    
with open('exoplanets.csv', 'r') as file:   #opening source file as read type
    data = file.readlines()
output = {}      # prepare output dictionary
for element, line in enumerate(data, 0):           # read line by line       
    items = line.replace('\n', '').split(',')      # split columns       
    if element == 0:                               # formatting inner dictionary's keys in a list: 'number', orbital_period', 'mass', 'distance', 'year'
        values = [key for key in items[1:]]
    else:

        if items[0] not in output.keys():           # add main key to the output dictionary: 'Radial Velocity', 'Imaging', 'Transit'
            output[items[0]] = {key : [] for key in values}
        for value, key in enumerate(values, 1):                  # add value to the inner dictionary
            if items[value] != '':                               # if the value is a valid number ( not a string) , convert it to float
                output[items[0]][key].append(float(items[value]))
for items in output.items():
    return (items)  

打印(parse_planets_file(文件))

【问题讨论】:

  • 如何在径向速度后添加分号而不是逗号
  • 请用您正在使用的编程语言标记

标签: python csv


【解决方案1】:

如果您的输入是这个元组,例如:

tp = ('径向速度', {'数字': [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 5.0], 'orbital_period': [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 5.0]})

dict_example = dict(tp[1]) 
# Converts the second part of the tuple ({'number'....}) structure to a dictionary. 
# Which in turn infers the types of the objects in the lists.

for key, value in dict_example.items():
    print(key, value)
    print(type(value[0]))

示例输出:

number [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 5.0]
<class 'float'>
orbital_period [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 5.0]
<class 'float'>

【讨论】:

猜你喜欢
  • 2018-06-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 2019-05-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多