输入一个文件路径,打开该文件(如:The Rivals in the Life.txt),并循环等待用户输入;
1.输入1,词频统计,输出出现次数最多的10个单词和其次数,并讲所有单词及此处保存到log.txt
2 输入2,复制文件到另一个目录下
3输入3,输出文件行数
3输入4,分别输出文件中字符最多的行和字符最少的行的字符个数
4输入5,在文件后追加字符串 “hello world”,并输出最后一行字符
5输入6,关闭该文件,打印“操作结束“
6输入其他字符,打印“无效字符!!请继续输入“
用python写,用几个函数实现。.
虽然不知道为什么你要几个函数实现,但我觉得我这函数创的够多了...
import os
import shutil
def count(string):
for special in [',', '.', ';', '!', '?', '\n']:
string = string.replace(special, ' ')
words = string.lower().split()
sort = {word: words.count(word) for word in set(words)}
sort = {word: sort[word] for word in sorted(sort.keys(), key=lambda _: sort[_], reverse=True)}
print('\n'.join([f'{word}\t\t{sort[word]}' for word in sort][:10]))
open('log.txt', 'w', encoding='utf-8').write('\n'.join([f'{word}\t\t{sort[word]}' for word in sort]))
def copy(origin, target):
shutil.copy(origin, target)
def rows(string):
print(len(string.split('\n')))
def character(string):
characters = [len(row) for row in string.split('\n')]
print(f'最多的行:{characters.index(max(characters)) + 1},字符个数:{max(characters)}')
print(f'最少的行:{characters.index(min(characters)) + 1},字符个数:{min(characters)}')
def append(origin, string):
open(origin, 'a', encoding='utf-8').write(string)
print(open(origin, 'r', encoding='utf-8').read().split('\n')[-1])
if __name__ == '__main__':
path = input('请输入文件路径:')
if os.path.exists(path) and os.path.isfile(path):
file = open(path, 'r', encoding='utf-8')
while 1:
file.seek(0)
num = input('请输入操作:')
if num == '1':
count(file.read().strip())
elif num == '2':
copy(path, f'test/{path}')
elif num == '3':
rows(file.read())
elif num == '4':
character(file.read())
elif num == '5':
append(path, 'hello world')
elif num == '6':
file.close()
print('操作结束')
break
else:
print('无效字符!!请继续输入')
else:
print('请输入正确的文件路径!')