基础Python。关于调用函数的快速问题
我在Python中遇到了一个基本的问题,希望能得到一些帮助 :-)
我有两个函数。一个是把文本文件转换成字典,另一个是把句子拆分成单独的单词:
(这是functiondoc.txt)
def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
现在我想写一个程序,使用这两个函数。
(这是program.txt)
from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
我现在遇到的问题是,我需要使用autoparts
这个函数来输出一些值(比如rear_bumper back_seat
),但我不太确定该怎么调用这个函数才能做到这一点。我觉得这应该不难,但我就是搞不定……
祝好,
Th
6 个回答
除了其他的提示和建议,我觉得你缺少了一个关键点:你的函数实际上需要返回一些东西。
当你创建autoparts()
或splittext()
时,想法是这个函数可以被调用,并且它可以(也应该)给你一些结果。
一旦你弄清楚了你希望函数输出什么,你就需要把这个结果放在return
语句里。
比如说,如果你希望splittext
返回一个单词列表,而不是直接打印出来,你就需要写这一行return words
。如果你希望autoparts
返回你构建的字典,你就应该用return dictionary
。
更准确地说(也为了回答你下面的评论/问题):你并不是想“返回一个生成字典的函数”;你想在函数内部返回这个字典。所以,你函数的最后一行应该是return dictionary
(在函数内部!)看看上面dbr的(被接受的!)解决方案。
我觉得你需要回到基础,读一些关于Python特别是编程的一般知识的书籍或网站,因为你对一些概念有点生疏。一个不错的资源是http://diveintopython3.ep.io/(当然还有其他的资源)。
一些快速要点:
- 你不应该把Python源文件命名为“.txt”,应该用“.py”。
- 你的缩进看起来不太对,但这可能只是Stack Overflow显示的问题。
- 你需要调用
autoparts()
这个函数来设置字典。 autoparts()
函数最好返回这个字典,这样其他代码才能使用它。- 打开文本文件时,应该使用
t
模式说明符。在某些平台上,底层的输入输出代码需要知道你在读取文本,所以你得告诉它。
正如大家所提到的,你需要给Python源文件加上py
的后缀。这样你的文件就会变成“functiondoc.py”和“program.py”。这样的话,import functiondoc
就能正常工作了(前提是它们在同一个文件夹里)。
关于autoparts
这个函数,最大的问题是你没有返回任何东西。另一个大问题是你用了错误的变量。
for line in list_of_parts:
k, v = line.split()
list1.append(k)
list2.append(v)
# k and v are now the last line split up, *not* the list you've been constructing.
# The following incorrect line:
dictionary = dict(zip(k, v))
# ...should be:
dictionary = dict(zip(list1, list2))
# ..although you shouldn't use zip for this:
你几乎不需要使用zip
,虽然在某些情况下它可能有用,但如果只是想创建一个简单的字典,这样做是不对的。与其这样做……
for line in list_of_parts:
...
dictionary = dict(zip(k, v))
……不如在循环之前先创建一个空字典,然后用mydict[key_variable] = value_variable来添加内容。
比如,我可能会这样写这个函数……
def autoparts():
# open() returns a file object, not the contents of the file,
# you need to use .read() or .readlines() to get the actual text
input_file = open('list_of_parts.txt', 'r')
all_lines = input_file.read_lines() # reads files as a list (one index per line)
mydict = {} # initialise a empty dictionary
for line in list_of_parts:
k, v = line.split()
mydict[k] = v
return mydict # you have to explicitly return stuff, or it returns None