<p>我在<code>function1</code>中创建了一个列表。我希望能够在<code>function2</code>中访问和修改它。如果没有全局变量,我怎么做?</p>
<p>这两个函数都不嵌套在另一个函数中,我需要能够在多个函数中为多个列表推广这一点。</p>
<p>我希望能够在其他函数中访问<code>word_list</code>和<code>sentence_starter</code>。</p>
<pre><code>def Markov_begin(text):
print create_word_lists(text)
print pick_starting_point(word_list)
return starting_list
def create_word_lists(filename):
prefix_dict = {}
word_list = []
sub_list = []
word = ''
fin = open(filename)
for line in fin:
the_line = line.strip()
for i in line:
if i not in punctuation:
word+=(i)
if i in punctuation:
sub_list.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(word)
word_list.append(sub_list)
sub_list = []
word = ''
sub_list.append(word)
word_list.append(sub_list)
print 1
return word_list
def pick_starting_point(word_list):
sentence_starter = ['.','!','?']
starting_list = []
n = 0
for n in range(len(word_list)-1):
for i in word_list[n]:
for a in i:
if a in sentence_starter:
starting_list += word_list[n+1]
print 2
return starting_list
def create_prefix_dict(word_list,prefix_length):
while prefix > 0:
n = 0
while n < (len(word_list)-prefix):
key = str(''.join(word_list[n]))
if key in prefix_dict:
prefix_dict[key] += word_list[n+prefix]
else:
prefix_dict[key] = word_list[n+prefix]
n+=1
key = ''
prefix -=1
print Markov_begin('Reacher.txt')
</code></pre>