俗话说,‘熟读唐诗三百首,不会吟诗也会吟’,请分析附件的唐诗300首文本文件。 完成下列功能:(部分功能需要使用jieba第三方库) 统计每首诗歌的作者,如果第一行输入‘作者’,第二行则输入一个整...
时间: 2023-07-16 16:16:49 浏览: 46
好的,我来为你分析附件的唐诗300首文本文件,并完成相应的功能。
首先,我们需要读取文本文件并将其处理成可供操作的数据。以下是读取文本文件的代码:
```python
with open('tangshi300.txt', 'r', encoding='utf-8') as f:
data = f.read()
```
接着,我们可以使用正则表达式来将每首诗歌的标题和内容分离,并将它们存储在一个列表中。以下是分离标题和内容的代码:
```python
import re
pattern = re.compile(r'(.+)[\n|\r\n](.+)[\n|\r\n]')
poems = pattern.findall(data)
```
现在,我们已经将每首诗歌的标题和内容分离并存储在了 `poems` 列表中。接下来,我们可以使用jieba第三方库来实现分词。以下是统计每首诗歌的作者的代码:
```python
import jieba
authors = {}
for poem in poems:
title = poem[0]
content = poem[1]
words = jieba.lcut(title)
if '作者' in words:
author = words[words.index('作者') + 1]
if author in authors:
authors[author] += 1
else:
authors[author] = 1
```
以上代码中,我们遍历了每一首诗歌,将其标题分词后,查找是否有“作者”这个词,并获取其后面的词作为作者名字。然后,我们使用字典来记录每位作者出现的次数。
最后,如果用户输入了“作者”这个词,我们将输出每位作者的名字和出现次数。以下是完整的代码:
```python
import re
import jieba
with open('tangshi300.txt', 'r', encoding='utf-8') as f:
data = f.read()
pattern = re.compile(r'(.+)[\n|\r\n](.+)[\n|\r\n]')
poems = pattern.findall(data)
authors = {}
for poem in poems:
title = poem[0]
content = poem[1]
words = jieba.lcut(title)
if '作者' in words:
author = words[words.index('作者') + 1]
if author in authors:
authors[author] += 1
else:
authors[author] = 1
while True:
user_input = input('请输入:')
if user_input == '作者':
for author, count in authors.items():
print(author + ': ' + str(count))
else:
break
```
希望以上代码能对你有所帮助!