将唐诗三百首中的诗分别写入独立的文件。

    1. 唐诗300
    2. 赵广辉精校版
    3. 010杜甫:佳人
    4. 绝代有佳人,幽居在空谷。
    5. 自云良家子,零落依草木。
    6. 关中昔丧乱,兄弟遭杀戮。
    7. 官高何足论,不得收骨肉。
    8. 世情恶衰歇,万事随转烛。
    9. 夫婿轻薄儿,新人美如玉。
    10. 合昏尚知时,鸳鸯不独宿。
    11. 但见新人笑,那闻旧人哭!
    12. 在山泉水清,出山泉水浊。
    13. 侍婢卖珠回,牵萝补茅屋。
    14. 摘花不插发,采柏动盈掬。
    15. 天寒翠袖薄,日暮倚修竹。
    16. 011杜甫:梦李白二首之一
    17. 死别已吞声,生别常恻恻。
    18. 江南瘴疠地,逐客无消息。
    19. 故人入我梦,明我长相忆。
    20. 君今在罗网,何以有羽翼?
    21. 恐非平生魂,路远不可测。
    22. 魂来枫林青,魂返关塞黑。
    23. 落月满屋梁,犹疑照颜色。
    24. 水深波浪阔,无使蛟龙得。
    25. 012杜甫:梦李白二首之二
    26. 浮云终日行,游子久不至。
    27. 三夜频梦君,情亲见君意。
    28. 告归常局促,苦道来不易。
    29. 江湖多风波,舟楫恐失坠。
    30. 出门搔白首,若负平生志。
    31. 冠盖满京华,斯人独憔悴。
    32. 孰云网恢恢,将老身反累。
    33. 千秋万岁名,寂寞身后事。
    1. def read_poem(file, path):
    2. """读唐诗300首,将每首诗切分开写入到文件中"""
    3. with open(file, 'r', encoding='utf-8') as poem:
    4. new_poem = '' # 空字符串
    5. for line in poem: # 遍历文件对象
    6. if line[:3].isdigit(): # 若前3个字符是数字,如010杜甫:佳人
    7. write_poem(new_poem, path) # 将读取的字符串写入文件
    8. new_poem = line # 用当前行构建新一首诗的字符串
    9. else:
    10. new_poem = new_poem + line # 不是数字开头的行拼接到当前诗的字符串上
    11. def write_poem(line, path):
    12. title = line.split(maxsplit=1)[0] # 根据空格切分一次,序号0的元素做为诗名,如010杜甫:佳人
    13. with open(path + title + '.txt', 'w', encoding='utf-8') as poem:
    14. poem.write(line) # 字符串写入文件
    15. if __name__ == '__main__':
    16. filename = '../data/txt/唐诗三百首.txt' # 源文件路径
    17. pathname = '../data/txt/poem/' # 存放切分后文件的路径
    18. read_poem(filename, pathname)

    例如读完第一首诗后,字符串内容为

    010杜甫:佳人

    绝代有佳人,幽居在空谷。
    自云良家子,零落依草木。
    关中昔丧乱,兄弟遭杀戮。
    官高何足论,不得收骨肉。
    世情恶衰歇,万事随转烛。
    夫婿轻薄儿,新人美如玉。
    合昏尚知时,鸳鸯不独宿。
    但见新人笑,那闻旧人哭!
    在山泉水清,出山泉水浊。
    侍婢卖珠回,牵萝补茅屋。
    摘花不插发,采柏动盈掬。
    天寒翠袖薄,日暮倚修竹。

    俗话说,‘熟读唐诗三百首,不会吟诗也会吟’,请分析附件的唐诗300首文本文件。
    完成下列功能:(部分功能需要使用jieba第三方库)
    1. 统计每首诗歌的作者,如果第一行输入‘作者’,第二行则输入一个整数n,输出出现最多的作者前n个,每行输出一个名字和出现次数,以空格间隔,程序结束
    2. 统计作者的名字出现的次数,如果第一行输入‘人物’,第二行则输入一个整数n,输出出现最多的作者前n个,每行输出一个名字和对应出现次数,以空格间隔,程序结束
    注:有的诗人在诗名或诗句中用到了别的诗人的名字。如’梦李白二首之一‘。因此第1,2项目之间的数据可能有所差异。
    3. 如果输入某个字符串编号,范围和格式在’010‘-’320‘之间(测试用例保证编号存在),输出对应该编号的诗句。
    输出格式:去掉首行诗歌编号,其余格式与文件中诗歌显示格式相同。
    4. 如果输入‘唐诗’,输出文件中的诗词数量,程序结束
    5. 飞花令,如果第一行输入’飞花’,则可以在第二行输入s中文字符(长度为1),然后按照在文件中出现的顺序,输出唐诗300首文件包含该中文字符的诗句(长度不超过7的诗句),每行一句。
    6. 如果非以上输入,输出‘输入错误’,程序结束
    poem.txt

    1. def read_file():
    2. """读唐诗文件,返回字符串"""
    3. with open('poem.txt', 'r', encoding='UTF-8') as f:
    4. return f.read()
    5. def author_dic(num):
    6. """统计每个作者诗的数量,以作者为键,诗的数量为值构建字典,返回按值降序排序列表"""
    7. author_ls = [x[3:] for x in poem_str.split() if x[:3].isdigit()]
    8. author_set = sorted(set(author_ls), key=author_ls.index) # 去掉重复作者名,并按出现顺序排序
    9. author_dict = {x: author_ls.count(x) for x in author_set} # 构建作者与作品数量的字典
    10. author = sorted(author_dict.items(), key=lambda x: x[1], reverse=True)[:num]
    11. return author
    12. def person_dic(num):
    13. """统计每个作者出现频率,以作者为键,作者出现次数为值构建字典,返回按值降序排序列表"""
    14. author_ls = [x[3:] for x in poem_str.split() if x[:3].isdigit()]
    15. author_set = sorted(set(author_ls), key=author_ls.index) # 去掉重复作者名,并按出现顺序排序
    16. person_dict = {x: poem_str.count(x) for x in author_set} # 构建作者与作者名出现数量的字典
    17. person = sorted(person_dict.items(), key=lambda x: x[1], reverse=True)[:num]
    18. return person
    19. def count_poems():
    20. """返回唐诗数量,每遇到3个数字开头为一首诗"""
    21. return len([x[:3] for x in poem_str.split('\n') if x[:3].isdigit()])
    22. def flying_flower(word):
    23. """接收字符串为参数,输出包含该字符串且长度小于7的诗句"""
    24. with open('poem.txt', 'r', encoding='UTF-8') as f:
    25. poem = sum([x.strip().split() for x in f if not x[:3].isdigit() and x], []) # 构建一维列表
    26. for line in poem:
    27. if word in line and len(line) <= 7:
    28. print(line)
    29. def get_poem(num):
    30. """输入诗的序号,切片返回该诗语句的字符串"""
    31. start = poem_str.index(num) + 3
    32. if num != '320':
    33. end = poem_str.index(str(int(num) + 1)) - 2 # 不是最后一首诗时,以下一首诗的序号出现位置为右边界
    34. else: # 序号320时,后面没有新的序号,以诗的长度为右边界
    35. end = len(poem_str)
    36. return poem_str[start:end]
    37. def judge(choice):
    38. if choice == '作者':
    39. n = int(input())
    40. for i in author_dic(n):
    41. print(i[0], i[1])
    42. elif choice == '人物':
    43. n = int(input())
    44. for i in person_dic(n):
    45. print(i[0], i[1])
    46. elif choice.isdigit() and choice <= '320' and len(choice) == 3:
    47. print(get_poem(choice))
    48. elif choice == '唐诗':
    49. print(count_poems())
    50. elif choice == '飞花':
    51. word = input()
    52. flying_flower(word)
    53. else:
    54. print('输入错误')
    55. if __name__ == '__main__':
    56. poem_str = read_file()
    57. operation = input()
    58. judge(operation)