写一个函数 def count_word(filename) 接受一个文件名并返回一个字典,其中键是文件中的单词,值是单词在文件中出现的次数。例如,如果文件包含以下内容: 用保龄球打网球比用网球打保龄球要难得多。
您的函数将返回以下字典:
{
"it": 2,
"is": 2,
"much": 1,
"more": 1,
"difficult": 1,
"to": 2,
"play": 1,
"tennis": 2,
"with": 2,
"a": 2,
"bowling": 1,
"ball": 2,
"than": 1,
"bowl": 1
}
你的函数需要打开给定的文件并处理它。你也应该照顾特殊字符。
如果文件为空或不存在,返回一个空字典。
到目前为止,这是我的代码,但我被卡住了。
def count_word(filename):
file = open(filename, 'r')
d = {}
for line in file:
line = line.strip().split()
for item in line:
if item in d:
d[item] += 1
else:
d[item] = 1
file.close()
return d
d = count_word('filename')
print(d)
为了提供更多见解,您能否提供给定代码时提供的错误:
def count_word(filename):
file = open(filename, 'r')
d = {}
for line in file:
line = line.strip().split()
for item in line:
if item in d:
d[item] += 1
else:
d[item] = 1
file.close()
return d
实际上这段代码应该提供字数统计。它可能无法处理文件不存在的边缘情况。
在你粘贴的代码中你有缩进问题,不确定这是格式问题还是你写 python 的方式。
为了获得更好的响应,请提供可测试的示例和错误。