簡體   English   中英

將單詞附加到列表

[英]Appending Words to a list

我試圖將不正確的單詞附加到列表中,但是當我在函數外部打印列表時它是空的,當我在函數內部打印它時它會為每個單詞打印一個列表。 如何讓列表在程序結束時只打印一次,其中包含不正確的單詞?

文件 1:這是我的拼寫檢查程序

文件 2:dis 是我的 spll cheker 程序

所以有3個不正確的詞應該添加到列表中

word_list = []

if cmdlength != 2:
    print ("Usage error, expected 2 args got " + str(cmdlength))
    exit()
else:
    try:
        f = open(sys.argv[1])
        f.close()
    except FileNotFoundError:
        print("File does not exist")
        exit()
    try:
        ff = open(sys.argv[2])
        ff.close()
    except FileNotFoundError:
        print("File does not exist")
        exit()
    word = ""
    with open(sys.argv[1],"r") as fh:
        while True:
            ch=fh.read(1)
            if ch == " " or ch == "\n" or ch == ":" or ch == ".":
                with open(sys.argv[2],"r") as fh2:
                    def check_word(word,fh2,word_list):
                        lines = fh2.readlines()
                        for line in lines:
                            x= re.search(word,line)
                            if x:
                                #correctwords
                                print(word + ": " + "0")
                                #count += 1
                            else:
                                #incorrect words
                                print(word, ": " , "1")
                                word_list.append(word)
                                #count2 += 1
                    check_word(word,fh2,word_list)
                word = ''
            else:
                word += ch
            if not ch:
                print(word)
                print("End of file")
                print(word_list)
                break

該函數缺少返回word_listreturn語句。 這應該工作

...
def check_word(word,fh2,word_list):
    lines = fh2.readlines()
    for line in lines:
        ...
        word_list.append(word)
        #count2 += 1
    return word_list

word_list = check_word(word,fh2,word_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM