while循环与try-except

时间:2019-03-17 19:13:20

标签: python while-loop try-except

如果输入的内容不正确,我想继续要求用户输入文件名。我已经用不正确的输入(缺少文件名)测试了该程序,但是提示用户输入错误消息并终止程序,而不是要求用户再次尝试。下面是不成功的代码(if的一部分)。谁能帮助我找出问题所在?

import nltk
from nltk.tokenize import word_tokenize
import re
import os
import sys




def main():
    while True:
        try:

            file_to_open =  input("insert the file you would like to use with its extension: ")

        except FileNotFoundError:

            print("File not found.Better try again")
            continue
        else:
            break


    with open(file_to_open) as f:
        words = word_tokenize(f.read().lower())

    with open ('Fr-dictionary2.txt') as fr:
        dic = word_tokenize(fr.read().lower())

        l=[ ]
        errors=[ ]
        for n,word in enumerate (words):
            l.append(word)
            if word == "*":
                exp = words[n-1] + words[n+1]
                print("\nconcatenation trials:", exp)
                if exp in dic:
                    l.append(exp)
                    l.append("$")
                    errors.append(words[n-1])
                    errors.append(words[n+1])
                else:
                    continue

2 个答案:

答案 0 :(得分:1)

即使路径本身在文件系统中不存在,也可以创建Path对象。在某些时候,您需要先询问Path对象,然后再退出while循环,然后在文件系统中找到它内部的路径。您不需要像下面这样的try / except块:

while True:
    p = Path(input("please input the path: "))
    if p.exists():
        break
    print("path does not exist, try again")

答案 1 :(得分:0)

问题是您正在“保护”仅询问名称的while循环。您可以将读数也放在try / except内以解决该问题:

while True:
   try:
       file_to_open =  input("insert the file you would like to use with its extension: ")
       with open(file_to_open) as f:
           words = word_tokenize(f.read().lower())
       break
   except FileNotFoundError:
       print("File not found.Better try again")