Python:如何从txt文件中获取字母,将它们的位置作为键存储在字典中作为元组,而将字母作为字符串存储为值?

问题描述 投票:1回答:1

我有一个txt文件,第一行的单个字母为“ M”,下一行为空白,第三行的字母为“ V”,后跟两个空格,然后同一行中的字母P。

喜欢这个:

M

V  P

我想将字母的位置存储为字典中的键作为元组,并将字母本身存储为值的字符串。我希望它看起来像这样:

{(0, 0): 'M', (0, 2): 'V', (3, 2): 'P'}

元组内的数字是x和y值,即txt在txt文件中的位置(坐标)。

此txt文件只是一个简单的测试文件,我希望能够对包含更多字母的较大txt文件使用此代码。

这里是我到目前为止的代码,但打印出来的结果不是我想要的:

''' Read map file to dictionary

Input: path to txt file
Output: Dictionary with tuple keys of (x,y) and content from map
'''
y = -1
x = 0
chartable = {}
with open(filename, 'r') as readfile:
    for line in readfile:
        y += 1
        data = line.split()
        char = (x,y)
        karakterliste = ""
        for i in range(0, len(data)):
            x += 1
            charlist += data[i]
        chartable[char] = charlist
print(chartable) 

结果:

{(0, 0): 'M', (1, 1): '', (1, 2): 'VP'}

python-3.x string dictionary tuples readfile
1个回答
0
投票

您无法使用,因为split()从您的数据中删除了空格,因此位置不正确。

您可以使用enumerate轻松完成此操作,而无需手动增加计数器:

with open("f.txt","w") as f:
    f.write("""M

V P""")

k = {}
with open("f.txt") as f:
    for line,text in enumerate(f):
        for pos, char in enumerate(text.rstrip()):
            if char != " ": # ignore spaces
                k[(pos,line)] = char

print(k)  # {(0, 0): 'M', (0, 2): 'V', (2, 2): 'P'}

请参见What does enumerate() mean?

不相关:我将使用(行,列)元组-而不是像您似乎使用的(列,行)元组。

© www.soinside.com 2019 - 2024. All rights reserved.