【问题标题】:Merging lines of a text file python合并文本文件python的行
【发布时间】:2021-10-03 11:47:51
【问题描述】:

我有一个文本文件,内容如下:

'artist
song
'artist2
song2
'artist3
song3
song4
'artist4
song5

我想在控制台打印:

song'artist
song2'artist2
song3'artist3
song4'artist3
song5'artist4

但是文本文件发生了变化,所以我不能只合并特定的行。 到目前为止,我有这个代码来合并艺术家姓名和艺术家姓名下方的第一首歌曲,但是当同一艺术家有多首歌曲时(如上面的示例文本文件所示),我希望它打印出所有该艺术家的歌曲后跟艺术家姓名,而不仅仅是第一首歌曲。

这是我当前的代码:

SongsFile = open('songs.txt', 'r')
Lines3 = SongsFile.readlines()
for line in Lines3:
    count += 1
    try:
        if line.startswith("\'"):
            x = count + 1
            at3.append(x)
            at4.append(line)
        if count = at3[0]:
            at3.clear()
            sa = line + at4[0]
            at4.clear()
            print(str(sa).replace("\n", " "))
    except:
        pass

这几乎可以工作,但不是输出我想要的(上面的示例),而是输出这个(如果使用了我上面给出的示例文件)

song'artist
song2'artist2
song3'artist3
song5'artist4

对不起,如果这令人困惑,我已尽力解释。

【问题讨论】:

    标签: python python-3.x file-handling txt


    【解决方案1】:

    我不知道您的代码有什么问题,但这似乎可行:

    with open('songs.txt') as f:
        lines = f.readlines()
        
    artist = ""
    song = ""
    out = []
    
    for line in lines:
        if line.startswith("'"):
            artist = line.strip()
        else:
            song = line.strip()
            out.append(song + artist) 
        
    text = "\n".join(out)     
    print(text)   
    

    【讨论】:

    • 对您所做的事情进行一些解释会很好。例如:“您只需要跟踪当前艺术家和当前歌曲。当一行以' 开头时,当前艺术家更改。如果没有,则打印当前行(歌曲),然后由现任艺术家创作”
    【解决方案2】:

    我想你可能想多了。看看下面的代码是不是你想要的...

    with open('songs.txt', 'r') as file:
        for line in file.readlines():
            if line.startswith("'"):
                artist = line
            else:
                print((line+artist).replace("\n",""))
    

    【讨论】:

    • 这也有效。如果你剥离两条线: line.strip()
    【解决方案3】:

    我不知道你想要实现什么。如果我知道您的用例,我想我可以做得更好。我尝试制作与您的示例完全相同的东西

    SongsFile = open('song.txt', 'r')
    lines = SongsFile.readlines()
    out = {}
    
    currArtist = ''
    for line in lines:
        line = line.replace('\n','')
        if line.startswith("\'"):
            currArtist = line
            out[currArtist] = []
        else:
            out[currArtist].append(line)
    
    
    for index, (artist, songs) in enumerate(out.items()):
        for song in songs:
            print(song,artist)
    

    结果:

    song 'artist
    song2 'artist2
    song3 'artist3
    song4 'artist3
    song5 'artist4
    

    【讨论】:

      猜你喜欢
      • 2014-12-02
      • 2023-03-20
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多