【发布时间】: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