【问题标题】:How to read and store values from a text file into a dictionary. [python]如何从文本文件中读取值并将其存储到字典中。 [Python]
【发布时间】:2013-07-20 11:05:00
【问题描述】:

我试图弄清楚如何打开一个文件,然后使用部件号将其内容存储到字典中。作为键,其他信息作为值。所以我希望它看起来像这样:

{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}

我能够将文件中的文本存储到一个列表中,但我不确定如何为一个键分配多个值。我试图在不导入任何模块的情况下做到这一点。我一直在使用基本的 str 方法、list 方法和 dict 方法。

【问题讨论】:

  • 你用的是什么版本的python?
  • 那是什么文件,只是普通的txt文件吗?
  • @nio 我用的是python 3,只是个txt文件

标签: python string list dictionary io


【解决方案1】:

您应该将值存储为列表或元组。像这样的:

textname = input("ENter a file")
thetextfile = open(textname,'r')
print("The file has been successfully opened!")
thetextfile = thetextfile.read()
file_s = thetextfile.split()
holder = []
wordlist = {}
for c in file_s:
   wordlist[c.split()[0]] = c.split()[1:]

【讨论】:

    【解决方案2】:

    您可以将文件读入这样的行列表中:

    lines = thetextfile.readlines()
    

    你可以用空格分割一行:

    items = somestring.split()
    

    这是一个如何将列表存储到字典中的主要示例:

    >>>mylist = [1, 2, 3]
    >>>mydict = {}
    >>>mydict['hello'] = mylist
    >>>mydict['world'] = [4,5,6]
    >>>print(mydict)
    

    像元组、列表和字典这样的容器可以作为它们的项相互嵌套。

    要迭代一个列表,你必须使用这样的 for 语句:

    for item in somelist:
        # do something with the item like printing it
        print item
    

    【讨论】:

    • 如果我用换行符分割文本,以后是否可以用每个单词分割每一行?
    • 是的,您可以使用thetextfile.read().splitlines() 读取整个文件,因此您可以获得行列表。然后您可以使用line.split() 将每一行用空格分隔。您可以自定义将使用参数拆分哪些字符,请阅读有关 python 字符串方法的信息。
    • 但是如果我拆分某些东西,它就会变成一个列表,并且拆分不适用于列表类型。
    【解决方案3】:

    对于像这样的txt 文件

    453     Sperving_Bearing    9900
    1342    Panametric_Fan      23400
    9480    Converter_Exchange  93859
    

    你可以这样做

    >>> newDict = {}
    >>> with open('testFile.txt', 'r') as f:
            for line in f:
                splitLine = line.split()
                newDict[int(splitLine[0])] = ",".join(splitLine[1:])
    
    
    >>> newDict
    {9480: 'Converter_Exchange,93859', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}
    

    您可以通过检查 line.startswith('-----') 是否删除 ----... 行。

    EDIT - 如果您确定前两行包含相同的内容,那么您可以这样做

    >>> testDict = {"Part no.": "Description,Price"}
    >>> with open('testFile.txt', 'r') as f:
            _ = next(f)
            _ = next(f)
            for line in f:
                splitLine = line.split()
                testDict[int(splitLine[0])] = ",".join(splitLine[1:])       
    >>> testDict
    {9480: 'Converter_Exchange,93859', 'Part no.': 'Description,Price', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}
    

    这会将第一行添加到代码中的testDict 并跳过前两行,然后照常继续。

    【讨论】:

    • newDict[int(splitLine[0])] = ",".join(splitLine[1:]).ValueError: int() 基数为 10 的无效文字:
    • 好的。您是否也在使用此代码解析第一行?因为那会给出这个错误。您需要单独解析它。我发布了示例文本文件。
    • 是的,我是。必须包括第一部分。
    • 如果您确定第一行永远不会改变,那么您可以将其添加到代码中的字典中并跳过前两行。稍后我将通过添加代码来解释如何。
    【解决方案4】:

    您的文件应如下所示:

    Part no.;Description,Price
    453;Sperving_Bearin,9900
    1342;Panametric_Fan,23400
    9480;Converter_Exchange,93859
    

    比你只需要添加一点代码:

    d = collections.OrderedDict()
    reader = csv.reader(open('your_file.txt','r'),delimiter=';')
    d = {row[0]:row[1].strip() for row in reader}
    for x,y in d.items():
         print x
         print y
    

    【讨论】:

      【解决方案5】:

      这是我的尝试,在 Python 2.x/3.x 上测试:

      import re
      
      def str2dict(filename="temp.txt"):
          results = {}
          with open(filename, "r") as cache:
              # read file into a list of lines
              lines = cache.readlines()
              # loop through lines
              for line in lines:
                  # skip lines starting with "--".
                  if not line.startswith("--"):
                      # replace random amount of spaces (\s) with tab (\t),
                      # strip the trailing return (\n), split into list using
                      # "\t" as the split pattern
                      line = re.sub("\s\s+", "\t", line).strip().split("\t")
                      # use first item in list for the key, join remaining list items
                      # with ", " for the value.
                      results[line[0]] = ", ".join(line[1:])
      
          return results
      
      print (str2dict("temp.txt"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多