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

Python 如何从文件中的每一行获取第二个和第四个字,python,Python,示例:文件将被称为“句子.dat”。它将有这些线路 名字#3是鲍勃 我叫玛丽 我的名字是凯特 名字#2是乔治 我想将它们保存到一个字典中,其中它们的编号是键,名称是值。这就是我目前所拥有的 file = open("Sentences.dat","r") dictNames = {} line = 1 while True: content = file.readlines()[line] split = content.split() dictNames[split[1

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

名字#3是鲍勃

我叫玛丽

我的名字是凯特

名字#2是乔治

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

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

这是另一种有效的方法

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:'Bob',7:'Marie',8:'Kate',2:'George'}

有什么问题吗?
循环中的
break
语句在哪里?在Python中,由于索引从
0
开始,所以将行初始化为
0
。接受的答案将在示例数据中的空行上中断,数字存储为字符串。我仍然认为我的回答可能对海报有所帮助。
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