簡體   English   中英

Python 不讓我添加到我的字典中?

[英]Python won't let me add to my dictionary?

我正在為 gcse 編寫代碼(不是測試的一部分),其中我有一個包含歌曲和制作它們的藝術家的外部文件,並給出每個單詞的第一個字母,正確猜測歌曲名稱。 在代碼(下面)中,我打開文件,並根據該行是否包含歌曲名稱或藝術家姓名,將其添加到具有正確編號的歌曲{} 或藝術家{} 字典中,但是當我收到此錯誤消息時通過我的終端運行它:

文件“task1gcse.py”,第21行,在songs[f"Song {lineNumber}"] = (("{line}".format(line=line)).strip("\\n")) # eg {' Song 4': 'Hey Jude'} TypeError: '_io.TextIOWrapper' 對象不支持項目分配

這是代碼:

# task 1 gcse 20 hr computing challenge
from random import *
import time


lineNumber = 0
artists = {}
artistNumber = 0
songs = {}
songNumber = 0
lines = {}


with open("songs.txt", "r") as songs: # opening the file
    for line in (songs):
        if line != "\n": # to ignore any blank lines
            lineNumber += 1
            lines[f"Line {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # so e.g. {'Line 2': 'John Lennon'}, but I won't be using this it's just for testing
            if lineNumber % 2 != 0: # if the line number is an even number, that line contains the name of a song
                songNumber += 1
                songs[f"Song {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # e.g. {'Song 4': 'Hey Jude'}
            elif lineNumber % 2 == 0: # if the line number is an odd number, that line contains the name of an artist
                artistNumber += 1
                artists[f"Artist {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # e.g. {'Artist 3': 'Avicii'}
        else:
            continue # if the line is blank; continue

這很奇怪,因為它只適用於 lineNumber 字典......請幫忙,任何人都會非常感激。 謝謝!

當您with open("songs.txt", "r") as songs: # opening the file ,您將覆蓋已經存在的songs字典 - 因此當您運行songs[f"Song {lineNumber}"] = ... ,您正在嘗試將其添加到打開的文件中。 重命名這些變量之一以解決此問題。 例如 -

# task 1 gcse 20 hr computing challenge
from random import *
import time


lineNumber = 0
artists = {}
artistNumber = 0
songs = {}
songNumber = 0
lines = {}


with open("songs.txt", "r") as songs_file: # opening the file
    for line in (songs_file):
        if line != "\n": # to ignore any blank lines
            lineNumber += 1
            lines[f"Line {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # so e.g. {'Line 2': 'John Lennon'}, but I won't be using this it's just for testing
            if lineNumber % 2 != 0: # if the line number is an even number, that line contains the name of a song
                songNumber += 1
                songs[f"Song {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # e.g. {'Song 4': 'Hey Jude'}
            elif lineNumber % 2 == 0: # if the line number is an odd number, that line contains the name of an artist
                artistNumber += 1
                artists[f"Artist {lineNumber}"] = (("{line}".format(line=line)).strip("\n")) # e.g. {'Artist 3': 'Avicii'}
        else:
            continue # if the line is blank; continue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM