【问题标题】:How do I remove \n from my python dictionary?如何从我的 python 字典中删除 \n?
【发布时间】:2014-04-06 06:19:34
【问题描述】:

所以我有一个类似的文本文件:

apples,green
tomatos,red
bananas,yellow

我将其用作字典的代码是

def load_list(filename):
    with open(filename, "rU") as my_file:
        my_list = {}
        for line in my_file:
            x = line.split(",")
            key = x[0]
            value = x[1]
            my_list[key] = value
        print my_list

工作正常,除了每个值都有 \n 添加到它的末尾,因为换行符。我尝试添加

.strip()

到x属性,但它导致属性错误(AttributeError:'dict'对象没有属性'strip')。

那么如何删除\n?

【问题讨论】:

    标签: python python-2.7 dictionary


    【解决方案1】:

    你应该在拆分之前strip,像这样

    x = line.rstrip("\n").split(",")
    

    我们在这里使用str.rstrip,因为我们只需要消除行尾的换行符。

    此外,您可以像这样立即解压缩键和值

    key, value = line.rstrip("\n").split(",")
    

    【讨论】:

      【解决方案2】:

      这是一个完整的示例,说明了该条的一般用途:

      def main():
      # Open a file named football.txt.
      infile = open('football.txt', 'r')
      
      # Read three lines from the file.
      line1 = infile.readline()
      line2 = infile.readline()
      line3 = infile.readline()
      
      Strip the \n from each string.
      line1 = line1.rstrip('\n')
      line2 = line2.rstrip('\n')
      line3 = line3.rstrip('\n')
      
      # Close the file.
      infile.close()
      
      # Print the data that was read into memory.
      print(line1)
      print(line2)
      print(line3)
      
      # Call the main function.
      main()
      

      假设您想将内容读入列表并去掉换行符。您可以执行以下操作:

      # This program reads a file's contents into a list.
      
      def main():
      # Open a file for reading.
      infile = open('football.txt', 'r')
      
      # Read the contents of the file into a list.
      football = infile.readlines()
      
      # Close the file.
      infile.close()
      
      # Strip the \n from each element.
      index = 0
      while index < len(football):
      football[index] = football[index].rstrip('\n')
      index += 1
      
      # Print the contents of the list.
      print(football)
      
      # Call the main function.
      main()
      

      第二个程序版本可以轻松地将列表替换为字典,只需进行一些非常小的更改。

      【讨论】:

        【解决方案3】:

        顺便说一句,如果您使用csv module,这是您可以避免的问题之一,因为它会为您去除线条:

        import csv
        
        def load_list(filename):
            with open(filename, 'r') as f:
                reader = csv.reader(f, delimiter=',')
                my_dict = {k:v for k,v in reader}
            return my_dict
        

        我还将您的变量名称更改为my_dict,因为它不是一个列表。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-01
          • 2019-06-13
          • 1970-01-01
          • 2021-02-13
          相关资源
          最近更新 更多