繁体   English   中英

while 循环中的错误与 try-except 相结合

[英]error in while loop combined with 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

即使文件系统中不存在路径本身,也可以创建 Path 对象。 在某些时候,在退出 while 循环之前,您需要询问 Path 对象其内部的路径是否存在于文件系统中。 你不需要 try/except 块这样做:

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

问题是您正在“保护”简单地询问名称的 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM