# 打开words.txt文件,并逐行读取
with open('D:\xingjian\words.txt', '\n') 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('D:\xingjian\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的单词写入当前路径下的一个新文件
为什么运行不出来?
第2行那里的那个文件名前加个r,以防止转义;
再把第2行的文件模式改为‘r’,因为'\n'不是文件模式;
最后把第28行的words.txt 改为long_words.txt,因为根据提示需要把长度大于10的单词写入long_words.txt中。
修改如下:
参考链接:
# 打开words.txt文件,并逐行读取
# https://zhuanlan.zhihu.com/p/260150620
with open(r'D:\xingjian\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的单词写入当前路径下的一个新文件
# https://www.englishtools.org/zh-cn/find-english-words-by-length
with open(r'D:\xingjian\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(测试数据文件,放在"d:\xingjian"目录下)
a
abc
good
Actor
About
Agree
anemometrograph
anesthesiometer
antihemorrheidal
斜线是转义符,要用两个;第2个参数是打开模式,'r'是读,'w'是写,根据需要修改。
打开文件这样改一下:
with open('D:\\xingjian\\words.txt', 'r') as file:
搜集了打开模式如下:
'r':只读模式(默认值),用于读取文件。
'w':写入模式,用于创建新文件或覆盖现有文件。
'a':追加模式,用于向文件末尾添加内容。
'x':创建模式,用于创建新文件,如果文件已存在则抛出异常。
'b':二进制模式,用于以二进制形式进行文件操作(可与上述模式组合使用)。