【问题标题】:Function creation - "Undefined name" - Python函数创建 - “未定义的名称” - Python
【发布时间】:2023-03-22 12:24:01
【问题描述】:

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

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, )

错误信息是undefined name 'hello'

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

谢谢!

【问题讨论】:

  • 这些“语音标记”被称为引号,是解释器区分字符串和标识符的唯一方法。是的,机器很笨,口译员也很笨,这就是生活。
  • 为什么要输入不带引号的参数?
  • 如果这个错误信息或其原因真的让你感到困惑,那么我怀疑你是否真的编写了这段代码,或者理解它。提示:例如,在if words[0]=="finish": 的行上,您是否想过尝试改用if words[0]==finish:?你能明白为什么那行不通吗?在等式的另一面,你能明白为什么words[0] 并不总是等于"w"吗?
  • @KarlKnechtel,显然代码不是他写的。
  • Stuart,老实说我不知道​​我当时为什么要写这个。听起来很嚣张。

标签: python string function python-2.7 undefined


【解决方案1】:

简单,你定义那个名字:

class hello:
  txt = "hello.txt"

但开个玩笑,函数调用中的所有参数值都是表达式。如果要按字面传递字符串,则必须使用引号创建字符串文字。 Python 不是像 m4 或 cpp 那样的文本预处理器,它希望整个程序文本都遵循它的语法。

【讨论】:

    【解决方案2】:

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

    据我所知,在输入字符串时需要告知函数定义,因此需要引号。

    我承认我完全不知道我对这一切如何运作的深度理解 - 我认为您几乎可以将任何种类的字母和/或数字作为论据,然后您可以在 操作它们> 函数定义。

    我的无知可能源于我对 Python 很陌生,我已经学习了 C++ 的编码基础知识,如果我没记错的话(那是一年多以前),函数是用每个参数定义的设置为他们的类型,例如

    int max(int num1, int num2)
    

    而在 Python 中,您并不会那样做。

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

    问题已解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-22
      • 2018-11-02
      • 1970-01-01
      • 2023-04-08
      • 2021-12-10
      • 2022-07-25
      • 2013-11-14
      相关资源
      最近更新 更多