繁体   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