我有一個 txt 檔案,其中包含以下格式的藝術家、歌曲和流派串列:
song 1
genre 1
artist 1
song 2
genre 2
artist 2
etc.
我得到了一個藝術家的名字,如果藝術家在檔案中,我必須回傳他們歌曲的名字。我設法撰寫的代碼是:
afile = open('music.txt')
header = afile.readline()
artists = afile.readlines()
afile.close()
for art in artists:
if art == artist:
我怎樣才能得到藝術家姓名上方兩行的歌曲名稱?一個藝術家也有可能用不同的歌曲多次出現。
uj5u.com熱心網友回復:
首先,將您的檔案讀入串列。我假設您的檔案格式是固定的:它包含
- 一行指定歌曲名稱
- 指定型別的行
- 指定藝術家的行
- 一個空行
- 重復
請注意,由于似乎沒有標題,因此您不需要初始 header = afile.readline()
假設您將檔案的所有行讀入一個名為 lines
lines = [line.strip() for line in afile]
# You could also do
# lines = afile.readlines()
# but that would leave behind trailing line breaks at the end of each line
現在,你知道
- 從第一行開始,每四行是歌曲名稱。因此,將
lines串列切片以每四行取一次,從第一行開始并將其保存為名為的串列songs
songs = lines[0::4]
- 對其他資訊做同樣的事情:
genres = lines[1::4]
artists = lines[2::4]
現在,我們可以zip()同時遍歷這些串列,并列印與我們正在尋找的藝術家匹配的歌曲:
look_for_artist = "artist 2"
print(f"Songs by {look_for_artist}:")
for artist, genre, song in zip(artists, genres, songs):
if artist == look_for_artist:
print(song, genre)
# if you know that every artist has only one song, you can break the loop here since you found it already
# break
如果您為一群藝術家這樣做,我建議您先將資料讀入字典(或collections.defaultdict)。然后,您可以查找給定藝術家的字典值,這比回圈串列要快得多。
為了說明單個藝術家可以有多首歌曲的情況,我們將使用一個字典,其中鍵是藝術家的名字,值是一個包含他們所有歌曲的串列。
import collections
lookup_dict = collections.defaultdict(list)
for artist, genre, song in zip(artists, genres, songs):
lookup_dict[artist].append((genre, song))
然后,您需要做的就是:
for genre, song in lookup_dict[look_for_artist]:
print(song, genre)
您可以不需要將整個檔案讀入串列,然后通過以四行為一組逐行讀取檔案將其處理為字典,但我將把它留給您作為練習。
uj5u.com熱心網友回復:
假設每個藝術家只有一首歌曲(或者您正在搜索第一首匹配),您可以這樣解決:
def check_artist(chosen_artist):
afile = open('music.txt')
while afile:
song = afile.readline()
afile.readline() # Ignore the second line
artist = afile.readline()
if atrist == chosen_artist:
return song.split("\n")
afile.readline() # Ignore the empty line
afile.close()
return "The artists do not have a song"
uj5u.com熱心網友回復:
從第二個元素開始(因為那是第一個藝術家所在的位置)并每隔 4 個元素掃描藝術家。如果 的i-th元素linelist匹配artist,則列印歌曲(位于i-2)。
for i in range(2, 100, 4):
if linelist[i] == artist:
print(linelist[i-2])
uj5u.com熱心網友回復:
到目前為止,所有答案都是有效的,但它們確實依賴于格式始終為 4 行的事實。如果缺少資料或有更多資料,以下代碼也可以正常作業:
music = []
with open("music.txt") as f:
for line in f:
line = line.split()
# continue if line is empty
if not line:
continue
key = line.pop(0)
value = ' '.join(line)
# check for keys
if key=='song':
music.append({key: value})
if key=='genre':
music[-1].update({key: value})
if key=='artist':
music[-1].update({key: value})
如果您的格式稍后包含另一個鍵(如'album' ),這也是可擴展的。
如果您使用的是 python3.10,您可以研究模式匹配以進一步簡化代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/335774.html
