[英]Using methods to append text file contents into a dictionary in Python?
So I have a .txt file and I want to use methods within this class, Map
, to append its contents into a aDictionary
. 所以我有一个.txt文件,我想在此类
Map
使用方法,将其内容附加到aDictionary
。
class Map:
def __init__(self, dataText):
self.dataText = dataText
self.aDictionary = {}
dataFile = open('data.txt', 'r')
c1 = Map(dataFile)
My data.txt
file looks something like this: 我的
data.txt
文件看起来像这样:
hello, world
你好,世界
how, are
如何
you, today
你今天
and I want aDictionary
to print this output: 我想要
aDictionary
打印此输出:
{how: are, you: today}
Im not very good at manipulating files as I continue to get type errors and what not. 我无法很好地处理文件,因为我继续遇到类型错误,但不是。 Is there an easy way of performing this task using methods within the class?
是否有使用类中的方法执行此任务的简便方法?
First you need to read the content of the file. 首先,您需要阅读文件的内容。 Once you have the content of the file, you could create the dictionary like this (assuming
content
contains the content of data.txt
): 一旦有了文件的内容,就可以像这样创建字典(假设
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)
Output 产量
{'you': 'today', 'how': 'are', 'hello': 'world'}
The idea is to iterate of over the lines using a for
loop, then check if the line is not empty ( if line
), in case the line is not empty, split on comma ( line.split(',')
) and remove the trailing whitespaces ( str.strip
) for each of the values in the list using map . 这个想法是使用
for
循环遍历各行,然后检查该行是否不为空( if line
),如果该行不为空, line.split(',')
逗号分割( line.split(',')
)并删除使用map在列表中每个值的尾随空白( str.strip
)。
Or using a 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)
To read the content of the file you can do the following: 要读取文件的内容,您可以执行以下操作:
content = self.dataText.read()
Further 进一步
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.