Skip to main content
 首页 » 编程设计

python:从txt文件的行创建字典

2025年05月04日21jpfss

对此很陌生,感谢您的耐心等待。

我有一首诗的 txt 文件。最终我想创建一个字典,这样我的键是行#,值是该行上的文本。例如,如果我的诗是这样的:

玫瑰是红色的,

紫罗兰是蓝色的。

我希望我的字典是:

dictionary = {1: 'Roses are red', 2: 'Violets are blue'}  

最终,我希望我的程序允许我通过输入行号(键)来搜索这首诗的一行。

我已经开始这样做了——

def getFile(): 
    prose = str(input('Please enter the file path for your text file: ')) 
 
    dictionary = {} 
 
    infile = open(prose, 'r') 
    for line in infile: 
        dictionary[line] += 1 
        print(dictionary) 
    infile.close() 
 
getFile() 

但是我迷路了,不知道下一步该做什么。我试过查找这个,我不明白这一点。任何帮助将非常感激。

请您参考如下方法:

您的问题在这里:

for line in infile:  # iterate over each line of text 
    dictionary[line] += 1  # this tries to use the text as a dict key instead of value 
    print(dictionary)  # I assume this is just here to display the current state of the dictionary eacy loop 

您需要一种方法来跟踪您所在的线路。值得庆幸的是,enumerate() 可以提供帮助:

for line_number, line in enumerate(infile): 
    dictionary[line_number] = line 
    print(dictionary)