【问题标题】:Using methods to append text file contents into a dictionary in Python?使用方法将文本文件内容附加到 Python 中的字典中?
【发布时间】:2019-05-01 00:39:16
【问题描述】:

所以我有一个 .txt 文件,我想使用此类 Map 中的方法将其内容附加到 aDictionary 中。

class Map:

    def __init__(self, dataText):
        self.dataText = dataText
        self.aDictionary = {}        

dataFile = open('data.txt', 'r')
c1 = Map(dataFile)

我的data.txt 文件如下所示:

你好,世界

怎么样

你,今天

我希望aDictionary 打印此输出:

{how: are, you: today}

我不擅长处理文件,因为我不断收到类型错误等等。有没有使用类中的方法执行此任务的简单方法?

【问题讨论】:

    标签: python class dictionary object


    【解决方案1】:

    首先您需要读取文件的内容。一旦你有了文件的内容,你可以像这样创建字典(假设content包含data.txt内容):

    content = """hello, world
    
    how, are
    
    you, today"""
    
    d = {}
    for line in content.splitlines():
        if line:
            key, value = map(str.strip, line.split(','))
            d[key] = value
    
    print(d)
    

    输出

    {'you': 'today', 'how': 'are', 'hello': 'world'}
    

    想法是使用for 循环遍历行,然后检查该行是否为空(if line),如果该行不为空,则以逗号分隔(line.split(','))和使用 map 删除列表中每个值的尾随空格 (str.strip)。

    或者使用dictionary comprehension

    content = """hello, world
    
    how, are
    
    you, today"""
    
    it = (map(str.strip, line.split(',')) for line in content.splitlines() if line)
    d = {key: value for key, value in it}
    print(d)
    

    要读取文件的内容,您可以执行以下操作:

    content = self.dataText.read()
    

    进一步

    1. Reading entire file in Python
    2. How to read a file line-by-line into a list?

    【讨论】:

    • 我得到一个 AttributeError 错误:'_io.TextIOWrapper' 对象在用'self.dataText'替换'content'时没有属性'splitlines';
    • 好的,成功了!你能解释一下你的第一种方法是如何工作的吗?我对 python 中的字典和文件操作很陌生。非常感谢!
    • @CosmicCat 更新了答案!
    猜你喜欢
    • 2021-01-26
    • 2019-03-14
    • 1970-01-01
    • 2015-10-22
    • 2018-02-14
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多