python - 将单词添加到列表中

标签 python python-3.x

我试图将不正确的单词附加到列表中,但是当我在函数外部打印列表时,它是空的,而当我在函数内部打印它时,它会打印每个单词的列表。如何在程序结束时只打印一次包含不正确单词的列表?

文件 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)

关于python - 将单词添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180800/

相关文章:

python - 使用python清理文本文件中的字符串编码问题

python - 在不使用 xticks 的情况下设置二维等高线图的轴值

python-3.x - 如何将 bool 数据类型为 True 的 numpy 零数组索引?

python - 是否可以控制函数在 python 中的执行方式?

检查方法参数的 Python 2/3 兼容方式

python-3.x - 使用 Homebrew 软件安装但未使用更新版本的 Python3

python - Pandas 合并具有不同名称的列并避免重复

python - Scikit learn 中的交叉验证与网格搜索

python - 无法从 S3 获取对象元数据。检查 aws Rekognition 中的对象键、区域和/或访问权限

python - 如何在 Python 3 中解析文件中的行时省略不需要的字符