01 这是原题
02 解答
这一题我觉得有一点难,所以写一下代码巩固。
2.1 这是我想的问题1代码:
f = open("八十天环游地球.txt") fi = open('八十天环游地球-章节.txt', 'w') for line in f: line_flag = line.split(' ')[0] if line_flag.startswith('第') and line_flag.endswith('章'): fi.write(line) fi.close() f.close()
2.2 这是我想的问题2代码:
import jieba f = open("八十天环游地球.txt") lines = f.readlines() lines_index = [] words = {} chapter = '' flag = 0 for line_i in range(len(lines)): line_start = lines[line_i].split(' ')[0] if line_start.startswith('第') and line_start.endswith('章'): chapter = line_start continue line = lines[line_i] word = jieba.lcut(line) for i in word: if len(i) >= 2: words[i] = words.get(i, 0) + 1 if line_i == len(lines) - 1: flag = 1 else: line_start1 = lines[line_i + 1].split(' ')[0] if line_start1.startswith('第') and line_start1.endswith('章'): flag = 1 if flag == 1: words = list(words.items()) words.sort(key=lambda x: x[1], reverse=True) print(chapter, words[0][0], words[0][1]) words = {} flag = 0 f.close()
2.3 这是标准答案: