【问题标题】:try except using files [closed]尝试除了使用文件[关闭]
【发布时间】:2016-03-21 01:28:25
【问题描述】:

处理一些需要使用 try-except-finally 的代码。它需要通读文件的行,将每一行分解为一个单词列表,然后循环遍历该行中的每个单词,并使用字典对每个单词进行计数。

这是我当前的代码:

try:
  input_filename = input("Enter a filename:") 
  input_file = open(input_filename, "r")
  content_str=input_file.read()
  words_list = content_str.split()

  for word in words_list:
    if word not in counts:
      counts[word] = 1
    else:
        counts[word] += 1
  input_file.close()    

except IOError:
  print ("The file temp doesn't exist.")

finally:
  pass 

【问题讨论】:

  • word = input_file.read() 行将整个文件读入一个字符串。然后该字符串成为count 的唯一条目。您需要逐行循环文件for line in input_file:,然后将每一行分解为单词。
  • 看看我编辑的代码对吗?
  • 还是很短
  • 请不要将您关于一个错误的问题编辑为关于另一个错误的问题。这样做,您使为响应第一个版本而编写的(正确,有用的)答案无效。如果您的跟进非常密切相关,您可以将其添加到问题的末尾,但不要去掉最初的部分。
  • 至于您的新问题,这取决于您要查找的密钥以及文件中的内容。您没有使用 counts 字典显示任何代码,也没有显示新异常的回溯,所以我怀疑有人可以帮助您。

标签: python-3.x exception


【解决方案1】:

您的问题在于您的if 声明。检查word 是否作为counts 中的键存在,如果存在,则将其设置为等于1但是,如果它不存在,则添加一个。因此,我假设您打算切换两者,请尝试以下代码:

count = {} 
try: 
  file_str = input("Enter a filename:")
  input_file = open(file_str, 'r') 
  word = input_file.read() 
  if word in counts: 
    counts[word] += 1
    print(counts)
  else: 
    counts[word] = 1
    print(counts) 
except KeyError: 
  print("Key error occured")  
except IOError: 
  print("The file temp doesn't exist.") 

【讨论】:

  • 这很奇怪我得到一个错误 >>> print (counts['This']) KeyError: 'This' Enter a filename:{'This is a test\nThis is only a test\n不要pass go\n不要收$200\n': 1}
  • 我不知道为什么我在拿起它的时候会收到一个键错误?
  • 您在评论中显示的字典只有一个键,即多行字符串'This is a test\nThis is only a test\nDo not pass go\Do not collect $200\n'。你的意思是按单词还是按行拆分?你可能需要一个循环!
  • 我现在用循环编辑了我的代码,但它缺少一些东西
  • 是他们的一种无需循环的方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多