【问题标题】:I have a list splitting problem in Python我在 Python 中有一个列表拆分问题
【发布时间】:2022-11-03 13:32:28
【问题描述】:

我正在将文件读入列表。现在我想要,我列表中的每个昏迷后,都应该有一个新的索引。到目前为止,所有内容都放在索引 0 中。

相关代码:

def add_playlist():
playlist_file_new =filedialog.askopenfilename(initialdir=f'C:/Users/{Playlist.username}/Music',filetypes=[('Playlistdateien','.txt')])
with open (playlist_file_new,'r') as filenew:
    filenew_content = list(filenew.readlines())
    print(filenew_content[0])

那么,我该怎么做才能在每个逗号之后开始一个新索引? 请帮助我,我提前谢谢你。如果这是一个非常基本的问题,我也很抱歉,我对编程真的很陌生。

【问题讨论】:

  • 所以基本上你的换行符是, 而不是\n。因此,不要使用readlines,而是使用read,这样您就可以将整个数据作为一个字符串。然后你可以split,的数据。
  • 文本文件是什么样的?如果我有您的输入数据,我可以提供一个有效的答案。
  • 那么问题是,它只打印一个字符,而不是整个字符串。所以整行'C:/Users/kevin/Music/y2meta.com - Big Boi - Kryptonite (VANE & ZVBXR Remix) (320 kbps).mp3' 变为索引 0 中的“(”,索引 1 中的“'”,索引 2 中的“C”等等。代码:filenew_content = filenew.read() filenew_content.split(",") print(filenew_content[1])

标签: python list file split readfile


【解决方案1】:

我没有尝试您的代码,但我会这样做:

with open (playlist_file_new,'r') as filenew:
    filenew_content = filenew.read()
    filenew_content_list = filenew_content.split(",")

那读完全的将文件的数据(请注意大于工作内存 (RAM) 的文件)放入变量 filenew_content。 它作为字符串返回。 Python 中的字符串对象具有split() 方法,您可以在其中定义一个字符串,在其中拆分较大的字符串。

【讨论】:

    【解决方案2】:

    不要使用list(),而是使用str.split()。为此,您不能使用 readlines(),因为它会返回行列表。

    你正在寻找这样的东西:

    filenew_content = playlist_file_new.read().split(",")
    

    这将获取文件对象,获取包含其内容的字符串,并将其拆分为列表,使用逗号作为分隔符。

    【讨论】:

      【解决方案3】:

      可能你想要的是.split() 函数:https://docs.python.org/3/library/stdtypes.html#str.split

      【讨论】:

        【解决方案4】:

        如果您的意思是将list[str] 变成list[str, str, str…],您可以使用str.split(str) 方法。请参阅以下内容:

        l = ["hello,world,this,is,a,list"]
        new_l = l[0].split(",")
        print(new_l)
        >>> ["hello", "world", "this", "is", "a". "list"]
        

        【讨论】:

          【解决方案5】:

          string.split(',') 方法应该可以工作。 例如

          # loop over all the lines in the file
          for line in filenew.readlines():
              items = line.strip().split(',')
              # strip strips the line of leading and trailing whitespace. 
              # split returns a tuple of all the strings created by 
              # splitting at the given character.
          
              # loop over all the items in the line
              for item in items:
                  # add them to the list
                  filenew_content.append(item)
          

          另请参阅:Python documentation for strings

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-25
            • 1970-01-01
            • 2018-05-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多