python - 如何在不返回函数的情况下访问函数内部的列表?

标签 python list

所以我不小心忘了在我的方法中包含一个返回语句,它在 10 小时后刚刚运行完毕,所以我不想再次运行它。有什么方法可以访问此函数中的 wordlist 吗?

def rm_foreign_chars(corpus):
    wordlist=[]
    for text in corpus:
        for sentence in sent_tokenize(text):
            wordlist.append(sentence)
            for word in word_tokenize(sentence):
                for c in symbols:

                    if c in word:
                        if sentence in wordlist:
                            wordlist.remove(sentence)
                            break

Symbols 是一个符号列表:symbols = '฿‑‒–――‖†‡•‰⁰⁷⁸₂₣℃™→↔∆∙≤⋅─■□▪►▼●◦◾★☎☺♣ ♦✓✔❖❖❗➡⠀ⱻ�ₒ'1

最佳答案

不幸的是,如果不使用一些真正的 hacky 方法并在内存中四处乱转,就无法在函数外部访问 wordList。相反,我们可以专注于使您的功能更快。这是我想出的:

def rm_foreign_chars(corpus):
    wordlist=[]
    for text in corpus:
        for sentence in sent_tokenize(text):
            if not any(c in word for word in word_tokenize(sentence) for c in symbols):
                wordlist.append(sentence)
    return wordlist

您还可以使wordlist 成为全局变量。我建议将其设置为全局的唯一原因是函数运行的时间长短(27 分钟仍然是很长的时间)如果函数在完成之前失败,您仍然可以从 wordlist 中获得一些东西。

def rm_foreign_chars(corpus):
    global wordlist
    for text in corpus:
        for sentence in sent_tokenize(text):
            if not any(c in word for word in word_tokenize(sentence) for c in symbols):
                wordlist.append(sentence)
    return wordlist

wordlist=[]

rm_foreign_chars(...)
# use wordlist here

关于python - 如何在不返回函数的情况下访问函数内部的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64905290/

相关文章:

python - “int”对象对于列表列表不可迭代

python - pandas 中任意分布的频率均值计算

python - Django Rest 框架 JWT

python - 从 List 中查找具有 key 对 'isGeo' :True 的字典

python - 如果字符串与列表名称匹配,则将数字附加到列表

Python,获取列表列表中最大值的索引

python - 具有列表值的列,在执行 str.len() 时消除空格

python - 根据值在 Python 字典中选择对象

python - 如何使用 Google Cloud 调度程序 Python api 创建作业

python - 如何将元组作为函数的参数传递