如何从文件中的每一行获取第二个和第四个字

2024-09-28 01:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

示例:文件将被称为“Sentences.dat”。它将有这些线路

Name #3 is Bob

Name #7 is Marie

Name #8 is Kate

Name #2 is George

我想将它们保存到一个dictionary,其中它们的编号是key,名称是value。这就是我目前所拥有的

file = open("Sentences.dat","r")
dictNames = {}
line = 1
while True:
    content = file.readlines()[line]
    split = content.split()
    dictNames[split[1]] = split[3]
    line = line + 1

Tags: 文件name示例islinesentencescontent线路
3条回答

这是另一种有效的方法

dictNames = {}
with open('Sentences.dat', 'r') as f:
    for line in f:
        words = line.split()
        dictNames[words[1]] = words[3]

试试这个。我还在代码中留下了一些注释

import io  # just for testing
from operator import itemgetter


# just for testing
file_content = """Name #3 is Bob

Name #7 is Marie

Name #8 is Kate

Name #2 is George
"""

# replace io.StringIO with open("Sentences.dat","r")
file = io.StringIO(file_content)  # just for testing

names = dict()

ig = itemgetter(1, 3)
with file:  # make sure file is closed after parsing using with
    for line in file:
        line = line.strip()
        # skip empty lines
        if not line:  
            continue
        # itemgetter is optional but fast and worth knowing
        hash_number, name = ig(line.split())
        number = int(hash_number[1:])
        names[number] = name

print(names)  # just for testing

结果:{3:'鲍勃',7:'玛丽',8:'凯特',2:'乔治'}

dictNames = {}
with open("Sentences.dat") as file:
    for line in file:
        parts = line.split()
        num = int(parts.lstrip('#'))
        dictNames[num] = parts[3]

相关问题 更多 >

    热门问题