2.歌词文件处理 读入歌词文件youngandbeautiful.txt,使用split函数将歌词分成单词。统计词频,将词频信息输出 至文件result.txt。 输出格式:以词频从高到低的顺序按行输出。对于相同词频的单词,按其在歌词中出现的先后顺序排列。每 行包括一个单词和它的词频,使用一个空格分隔。文件均使用utf-8编码。 输出格式示例: apple10 more5 happy5 you3 is2
时间: 2023-06-18 18:07:31 浏览: 55
以下是实现该功能的 Python 代码:
```python
# 读入歌词文件
with open('youngandbeautiful.txt', 'r', encoding='utf-8') as f:
lyrics = f.read()
# 将歌词分割成单词
words = lyrics.split()
# 统计词频
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 按词频从高到低排序
sorted_word_count = sorted(word_count.items(), key=lambda x: (-x[1], words.index(x[0])))
# 将词频信息输出至文件result.txt
with open('result.txt', 'w', encoding='utf-8') as f:
for word, count in sorted_word_count:
f.write(word + ' ' + str(count) + '\n')
```
代码中,首先读入歌词文件,并使用 split 函数将歌词分割成单词,然后使用一个字典 word_count 统计每个单词的词频。接着,使用 sorted 函数按照词频从高到低排序,排序时如果词频相同则按照单词在歌词中出现的先后顺序排列。最后,将排序后的词频信息输出至文件 result.txt,每行包括一个单词和它的词频,使用一个空格分隔。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)