Skip to main content
 首页 » 编程设计

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

2024年11月24日9bjzhanghao

如果输入不正确,我想继续要求用户输入文件名。我用不正确的输入(拼写错误的文件名)测试了程序,但没有要求用户重试,而是提示错误消息并且程序终止。不成功的代码(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 

请您参考如下方法:

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

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