【问题标题】:Iterating the lines of a text file and then returning a dictionary in python?迭代文本文件的行,然后在 python 中返回字典?
【发布时间】:2011-04-03 03:53:49
【问题描述】:

我应该编写一个函数来打开一个数据文件,其中每个数据文件都类似于:

WH239,  Mountain Bike Wheel,            5000

其中id为WH239,描述为'Mountain Bike Wheel',费用为5000

然后,该函数将 id 分配为字典中的键,并将描述和价格分配为值,我想要做的是创建一个循环,将每一行放入一个列表中,去除所有空格,然后分配适当的索引字典的键和值,到目前为止我被困在这个:

def load_parts(): 
    doc = open('parts.txt', 'U')
    data = doc.read()
    data = data.split('\n')
    for item in data:    
        formatted_line = item.split(',')

我还没有开始剥离空白,因为当我告诉它在 for 循环中返回 formatted_line 时,它​​只返回数据的第一个元素。

我只能在 python 中使用内置命令,感谢任何帮助!

对不起,是的,是作业,不出所料,我不期待答案,只是方向正确的一点,我只能使用内置库中的函数。

【问题讨论】:

  • 如果是作业,请用homework标签标记。
  • 只有built-in 命令?或者您是否允许使用标准 Python 库的元素,例如 csv 模块?
  • 请自己做作业。具体问题出在哪里?

标签: python file loops


【解决方案1】:

你应该尝试类似的东西

doc = open('your file')
for line in doc.readline():
    if len(line) != 0:
        line.split(',')

【讨论】:

  • 谢谢!这正是我所需要的!
  • @Sean:Welcome to StackOverflow。 “谢谢!”最好在最有帮助的答案旁边用绿色勾号表示。
【解决方案2】:
code:
    import sys,os
    lis = []
    my_dict = {}

    def load():
        doc = open('/home/sahil/python/file.txt','U')
        data = doc.read()
        data = data.split('\n')
        for item in data:
             formatted_line = item.split(',')
             lis.append(formatted_line)
        return lis  



     def assign(enter_the_list):
         length = len(enter_the_list)-1
         for item in range(length):
             k= enter_the_list[item]
             my_dict[k[0]] = k[1].strip(' ')+' '+k[2].strip(' ')
         print my_dict

     if __name__ == "__main__":
         k = load()
         assign(k)

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多