【问题标题】:Creating a dictionary from a text file using each line使用每一行从文本文件创建字典
【发布时间】:2016-03-09 02:16:44
【问题描述】:

我的.txt 文件如下所示:

 1 2
 3 4
 5 6
 7
 a 8
 9 10

我需要检查一行上的两个值是否都是整数,如果不是,它会给出错误并继续。

然后将其更改为字典,使用左侧的值作为键,右侧的值作为值,但前提是两个值都是整数。

如果它们都不是整数,并且 key 已经存在,我必须添加一个值。如果键不存在,我会同时添加一个值和一个键。

在此之前,我需要使用原始输入打开文本文件,如果插入无效输入,则会出现错误。 (我得到了这部分工作)

这是我目前所拥有的:

while True:
    try:
        fileName=raw_input('File name:')
        File2=open(fileName,'r+')
        break
    except IOError:
        print 'Please enter valid file name!'

for line in File2:
    if line==int:
        continue
else:
    print 'This line does not contain a valid Key and Value'

myDict = {}
for line in File2:
    line = line.split()
    if not line:  
        continue
    myDict[line[0]] = line[1:]
    print line

【问题讨论】:

  • 您的要求没有意义。首先你说如果两个字符串都是整数,你只添加到字典中,然后你说 "如果它们不是两个整数,并且键已经存在,我必须添加一个值。如果键不存在我同时添加一个值和一个键。” - 那么具体的要求是什么?
  • 您的陈述令人困惑和模棱两可。我认为为您的给定输入添加示例输出会有所帮助。

标签: python python-2.7 exception dictionary


【解决方案1】:

以下内容有望让您走得更远。当文件中的值不是整数时,不清楚您要做什么。下面显示了您可以添加的位置:

import os

myDict = {}

while True:
    fileName = raw_input('File name: ')
    if os.path.isfile(fileName):
        break
    else:
        print 'Please enter valid file name!'

with open(fileName, 'r') as f_input:
    for line_number, line in enumerate(f_input, start=1):
        cols = line.split()
        if len(cols) == 2:
            try:
                v1 = int(cols[0])
                v2 = int(cols[1])
                myDict[v1] = v2
            except ValueError, e:
                print "Line {} does not use integers - {}, {}".format(line_number, cols[0], cols[1])
                # If they're not both integers, and key is already present I have to add a value
                # <Add that here>
        else:
            print "Line {} does not contain 2 entries".format(line_number)

print myDict

因此,对于您的示例文件,这将为您提供以下类型的输出:

File name: x
Please enter valid file name!
File name: input.txt
Line 4 does not contain 2 entries
Line 5 does not use integers - a, 8
{1: 2, 3: 4, 5: 6, 9: 10}

我建议你使用 Python 的 with 命令。这将在之后自动为您关闭文件。

【讨论】:

  • 这正是我想要的。对不起,英语不是我的第一语言!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 2011-05-20
  • 2021-11-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
相关资源
最近更新 更多