Python 如何访问函数中的列表而不返回它?

Python 如何访问函数中的列表而不返回它?,python,list,Python,List,所以我不小心忘了在我的方法中包含return语句,它在10小时后才运行完,所以我不想再次运行它。有没有办法访问此函数中的单词列表 def rm_foreign_chars(corpus): wordlist=[] for text in corpus: for sentence in sent_tokenize(text): wordlist.append(sentence) for word in word_tok

所以我不小心忘了在我的方法中包含return语句,它在10小时后才运行完,所以我不想再次运行它。有没有办法访问此函数中的
单词列表

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=''.‑‒–-“†”•⁰⁷⁸₂₣℃™→↔∆∙≤⋅─■□▪►▼●◦◾★☎☺♣♦✓✔❖❗➡⠀ⱻ�ₒ'1

如果不返回列表,则无法执行此操作。另一种方法是创建一个包含函数的类,并将列表存储为
self
的属性

class Characters:
    def __init__(self, corpus):
        self.corpus = corpus
        self.wordlist = []

    def foreign_chars(self):
        pass
        # Function code goes here
        # Be sure to replace corpus and wordlist
        # With their respective self attributes

chars = Characters()
chars.foreign_chars()
words = chars.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分钟仍然很长)如果函数在完成之前失败,您仍然可以从
单词列表
中获得一些信息

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

不。它消失了。修复你的bug并开始重新运行。rip list,这就是为什么你在实现之前测试你的函数!函数完成后,局部变量将被垃圾收集,因此可能不会。对于以后的重播,与其将每个句子都添加到列表中,然后在其任何单词中包含符号时将其删除,为什么不简单地将每个没有符号的句子都写入某个文件?没有丢失结果的风险,即使进行了一半,也不会太复杂,所以应该要快得多。你有一种非常复杂和低效的方法来过滤带有符号的句子。它做了很多不必要的工作。清理一下,下一次跑步应该比10小时快得多。谢谢,从10小时到27分钟!开销是由remove()函数引起的吗?@mojbius可能是单词列表中remove和
if语句的组合。很高兴这对你有好处