用Pytnon在网页http://code.web.idv.hk/charset/csws1.php上获取通用规范汉字(TGhanzi.txt)每个汉字的部首,并写入文件
时间: 2023-12-18 16:03:05 浏览: 37
首先,需要用requests库从网页上获取TGhanzi.txt文件的内容。然后,需要用正则表达式从文件中提取每个汉字,并用字典记录每个汉字的部首。最后,将字典写入文件。
以下是示例代码:
```python
import requests
import re
# 获取TGhanzi.txt文件内容
url = 'http://code.web.idv.hk/charset/csws1.php?charset=TGhanzi'
response = requests.get(url)
content = response.text
# 用正则表达式提取每个汉字
pattern = re.compile(r'[\u4e00-\u9fa5]')
hanzi_list = pattern.findall(content)
# 记录每个汉字的部首
bushou_dict = {}
for hanzi in hanzi_list:
url = f'http://xh.5156edu.com/html3/{ord(hanzi):X}.html'
response = requests.get(url)
content = response.text
pattern = re.compile(r'<a href="http://xh.5156edu.com/html3/\d+.html">(.*?)</a>')
bushou = pattern.search(content).group(1)
bushou_dict[hanzi] = bushou
# 将字典写入文件
with open('bushou.txt', 'w', encoding='utf-8') as f:
for hanzi, bushou in bushou_dict.items():
f.write(f'{hanzi}\t{bushou}\n')
```
运行以上代码后,将在当前目录下生成一个名为bushou.txt的文件,每行表示一个汉字和它的部首,用制表符分隔。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)