python 编程题:下载附件文本,读取该文件,统计各个字符出现的次数并打印,最后单独打印出由文本里只出现1次的字符组成的字符串。
时间: 2024-06-08 21:09:10 浏览: 9
以下是代码实现:
```python
import urllib.request
# 下载附件文本
url = "https://raw.githubusercontent.com/ChenjieGu/Python-Basics/master/test.txt"
urllib.request.urlretrieve(url, "test.txt")
# 读取文件
with open("test.txt", "r") as f:
text = f.read()
# 统计各字符出现的次数
char_count = {}
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 打印字符出现次数
for char, count in char_count.items():
print(f"{char}: {count}")
# 打印只出现1次的字符组成的字符串
unique_chars = [char for char, count in char_count.items() if count == 1]
unique_str = "".join(unique_chars)
print("Unique characters: ", unique_str)
```
以上代码首先使用 `urllib.request` 模块下载附件文本,然后使用 Python 内置的文件读取方法 `open` 和 `read` 读取文本内容。接下来使用一个字典 `char_count` 统计每个字符出现的次数,最后通过筛选出只出现一次的字符,使用列表推导式和 `join` 方法得到只出现一次的字符构成的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)