俗话说,‘熟读唐诗三百首,不会吟诗也会吟’,请分析附件的唐诗300首文本文件。 完成下列功能:(部分功能需要使用jieba第三方库) 统计每首诗歌的作者,如果第一行输入‘作者’,第二行则输入一个整...
时间: 2023-10-04 18:04:02 浏览: 45
好的,我可以帮你完成这个任务。首先,我们需要读取附件的唐诗300首文本文件,并将其存储为一个字符串列表。
```python
with open('tangshi300.txt', 'r', encoding='utf-8') as f:
tangshi = f.readlines()
tangshi = [line.strip() for line in tangshi]
```
接下来,我们可以定义一个函数来统计每首诗歌的作者。我们可以遍历每一行诗歌,当遇到“作者:”时,就将作者记录下来。最后将作者列表返回即可。
```python
def get_authors(tangshi):
authors = []
for line in tangshi:
if line.startswith('作者:'):
author = line.replace('作者:', '').strip()
authors.append(author)
return authors
```
如果第一行输入“作者”,第二行输入一个整数n,则我们可以使用Counter类统计每个作者出现的次数,并返回前n个出现次数最多的作者及其出现次数。
```python
from collections import Counter
if input() == '作者':
n = int(input())
authors = get_authors(tangshi)
author_count = Counter(authors)
top_n = author_count.most_common(n)
for author, count in top_n:
print(author, count)
```
如果你想要使用jieba第三方库进行分词,可以按照以下步骤进行:
首先,我们需要安装jieba库,可以使用以下命令进行安装:
```
!pip install jieba
```
然后,我们可以定义一个函数来分析每首诗歌的内容。我们可以使用jieba库进行分词,并将分词结果存储为一个字符串列表。然后,我们可以遍历每个分词,并统计出现次数最多的前n个分词。
```python
import jieba
def analyze_poem(poem, n):
words = []
for line in poem:
words += jieba.lcut(line)
word_count = Counter(words)
top_n = word_count.most_common(n)
for word, count in top_n:
print(word, count)
```
如果第一行输入“分析”,第二行输入一个整数n和一首诗的编号m,则我们可以使用上面的函数分析第m首诗的内容,并返回出现次数最多的前n个分词。
```python
if input() == '分析':
n, m = map(int, input().split())
poem = tangshi[(m-1)*4+1:(m-1)*4+4]
analyze_poem(poem, n)
```
完整代码如下:
```python
from collections import Counter
import jieba
with open('tangshi300.txt', 'r', encoding='utf-8') as f:
tangshi = f.readlines()
tangshi = [line.strip() for line in tangshi]
def get_authors(tangshi):
authors = []
for line in tangshi:
if line.startswith('作者:'):
author = line.replace('作者:', '').strip()
authors.append(author)
return authors
def analyze_poem(poem, n):
words = []
for line in poem:
words += jieba.lcut(line)
word_count = Counter(words)
top_n = word_count.most_common(n)
for word, count in top_n:
print(word, count)
if input() == '作者':
n = int(input())
authors = get_authors(tangshi)
author_count = Counter(authors)
top_n = author_count.most_common(n)
for author, count in top_n:
print(author, count)
if input() == '分析':
n, m = map(int, input().split())
poem = tangshi[(m-1)*4+1:(m-1)*4+4]
analyze_poem(poem, n)
```
注意,由于jieba库是基于Python2开发的,因此在Python3中使用时需要加上“from __future__ import unicode_literals”这一行。