【发布时间】:2021-02-27 11:29:39
【问题描述】:
我正在尝试通过将单词数除以句号数来计算 .txt 文件中句子的平均长度:-
def divide(x, y):
return x / y
file = open("File One.txt", "r")
data = file.read()
words = data.split()
print('Number of words in text file:', len(words))
count = data.count('.')
print("Number of full stops:", count)
num1 = words
num2 = count
print("Average sentence length:", divide(num1, num2))
但我最终得到:-
Number of words in text file: 25
Number of full stops: 3
Traceback (most recent call last):
File "C:\Users\Jonathan\Desktop\Data\stripped down.py", line 16, in <module>
print("Average sentence length:", divide(num1, num2))
File "C:\Users\Jonathan\Desktop\Data\stripped down.py", line 2, in divide
return x / y
TypeError: unsupported operand type(s) for /: 'list' and 'int'
任何帮助或建议将不胜感激。
【问题讨论】:
-
您的
num1被定义为单词列表本身,而不是其长度。这个问题基本上是笔误。另外,divide的意义何在?定义一个函数而不是仅仅使用操作符需要更多的输入,这只会降低代码的可读性。