简体   繁体   English

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

[英]error in while loop combined with try-except

I want to keep asking the user to enter the file name if the input entered is incorrect.如果输入的输入不正确,我想不断要求用户输入文件名。 I've tested the program with incorrect input (misspelt file name) but instead of asking the user to try again an error message is prompted and the program terminates.我已经用不正确的输入(拼写错误的文件名)测试了程序,但没有要求用户重试,而是提示错误消息并且程序终止。 The unsuccessful code (part of if) is below.不成功的代码(if 的一部分)如下。 Can anyone help me to detect what's wrong?谁能帮我找出问题所在?

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

It's possible to create a Path object even if the path itself does not exist in your filesystem.即使文件系统中不存在路径本身,也可以创建 Path 对象。 At some point, you need to ask the Path object if the path inside it exists in the filesystem, before exiting the while loop.在某些时候,在退出 while 循环之前,您需要询问 Path 对象其内部的路径是否存在于文件系统中。 You won't need the try/except block doing it like this:你不需要 try/except 块这样做:

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

The problem is that you are "protecting" the while loop where the name is simply asked.问题是您正在“保护”简单地询问名称的 while 循环。 You could instead put the reading also inside the try / except to handle the problem:您可以改为将读数也放在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