这是代码
# 打开words.txt文件,并逐行读取
with open('words.txt', 'r') as file:
lines = file.readlines()
# 统计文件总行数
total_lines = len(lines)
print(f"文件总行数为:{total_lines}")
# 统计最长单词的长度
max_length = 0
for line in lines:
words = line.split()
for word in words:
if len(word) > max_length:
max_length = len(word)
print(f"最长单词的长度为:{max_length}")
# 统计首字母为大写A的单词
upper_A_words = []
for line in lines:
words = line.split()
for word in words:
if word[0] == 'A' and word[0].isupper():
upper_A_words.append(word)
print(f"首字母为大写A的单词有:{upper_A_words}")
# 将长度超过10的单词写入当前路径下的一个新文件
with open('long_words.txt', 'w') as new_file:
for line in lines:
words = line.split()
for word in words:
if len(word) > 10:
new_file.write(word + '\n')
print("长度超过10的单词已写入long_words.txt文件")
题目为:编程要求:
要求:遍历文本文件words.txt中的所有行
(2)统计文件总行数
(3)统计最长单词的长度
(4)统计首字母为大写A的单词
(5)将长度超过10的单词写入当前路径下的一个新文件
为什么这个代码无法运行?
你这个报错和给的代码不符合呀。