写出最后一步将票数写入文件的代码
时间: 2024-03-24 19:40:19 浏览: 21
好的,下面是将排序后的得票结果写入文件的完整代码:
```python
# 统计票数
polls_file = open("polls.txt", "r")
votes = {}
for line in polls_file:
name, *books = line.strip().split()
for book in books:
if book in votes:
votes[book] += 1
else:
votes[book] = 1
polls_file.close()
# 按得票数从高到低排序并输出结果到文件
result_file = open("result.txt", "w")
sorted_votes = dict(sorted(votes.items(), key=lambda item: item[1], reverse=True))
for book, vote in sorted_votes.items():
result_file.write("{}:{}\n".format(book, vote))
result_file.close()
```
代码首先打开 "polls.txt" 文件,并创建一个空字典 votes 来记录每本书的得票数。然后,对于文件中的每一行记录,使用 split() 方法将投票人 name 和他所投的书 books 分开,并逐一遍历 books 中的每本书。如果字典 votes 中已经存在该书的记录,则将其得票数加一;否则,将其得票数设为 1。
接下来,代码打开 "result.txt" 文件,并使用 sorted() 函数将 votes 中的记录按照得票数从高到低排序,并存储到 sorted_votes 字典中。最后,遍历 sorted_votes 中的每一项,并使用 write() 方法将每本书和其得票数写入 "result.txt" 文件中,每行末尾加上换行符 "\n"。写入完成后,关闭文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)