功能创建 - "未定义的名称" - Python

时间:2016-02-15 13:40:48

标签: python string function python-2.7 undefined

我正在编写一些代码来读取文本文件中的单词并将它们分类到字典中。它实际上运行良好,但在此参考它是:

def find_words(file_name, delimiter = " "):
"""
A function for finding the number of individual words, and the most popular words, in a given file.
The process will stop at any line in the file that starts with the word 'finish'.
If there is no finish point, the process will go to the end of the file.


Inputs:  file_name: Name of file you want to read from, e.g. "mywords.txt"
         delimiter: The way the words in the file are separated e.g. " " or ", "
                  : Delimiter will default to " " if left blank.

Output: Dictionary with all the words contained in the given file, and how many times each word appears.

"""

words = []
dictt = {}
with open(file_name, 'r') as wordfile:
    for line in wordfile:
        words = line.split(delimiter)
        if words[0]=="finish": 
            break             

        # This next part is for filling the dictionary 
        # and correctly counting the amount of times each word appears.

        for i in range(len(words)):
            a = words[i]
            if a=="\n" or a=="":   
                continue
            elif dictt.has_key(a)==False: 
                dictt[words[i]] = 1  
            else:
                dictt[words[i]] = int(dictt.get(a)) + 1 
return dictt

问题是它只有在参数以字符串文字形式给出时才有效,例如,这有效:

test = find_words("hello.txt", " " )

但这并不是:

test = find_words(hello.txt, )

错误消息是未定义的名称' hello'

我不知道如何更改函数参数,以便我可以在没有语音标记的情况下输入它们。

谢谢!

2 个答案:

答案 0 :(得分:0)

很简单,您可以定义该名称:

class hello:
  txt = "hello.txt"

但是开玩笑说,函数调用中的所有参数值都是表达式。如果你想从字面上传递一个字符串,你必须使用引号来创建一个字符串文字。 Python不是像m4或cpp这样的文本预处理器,并且期望整个程序文本遵循其语法。

答案 1 :(得分:0)

事实证明,我只是误解了被问到的内容。我现在已经被课程负责人澄清了。

正如我现在完全知道的那样,在输入字符串时需要告诉函数定义,因此需要引号。

我完全无视我对这一切是如何运作的深入理解 - 我认为你几乎可以把任何各种各样的字母和/或数字作为一个参数,然后你可以在 >功能定义。

我的无知可能源于这样一个事实:我对Python很陌生,在C ++上学习了我的编码基础知识,如果我没记错的话(一年多以前),每个参数都定义了函数被特别设置为他们的类型,例如

int max(int num1, int num2)

而在Python中,你不会那样做。

感谢您的帮助尝试(和嘲笑!)

问题现已排序。