统计指定文本中的蒙古文单词出现的次数并从高到低排序,并将排序结果写到文本件中python
时间: 2024-03-18 22:41:41 浏览: 20
可以使用Python中的Counter和re模块来实现这个需求。
以下是代码示例:
```python
import re
from collections import Counter
# 读取文本文件内容
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用正则表达式提取蒙古文单词
mongolian_words = re.findall("[\u1800-\u18AF]+", text)
# 使用Counter统计单词出现次数
word_count = Counter(mongolian_words)
# 按照出现次数从高到低排序
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 将排序结果写入文件
with open('output.txt', 'w', encoding='utf-8') as f:
for word, count in sorted_words:
f.write(f"{word}: {count}\n")
```
在这个示例中,我们首先读取了文本文件的内容,并使用正则表达式提取出所有的蒙古文单词。然后,我们使用Counter统计每个单词出现的次数,并按照出现次数从高到低排序。最后,我们将排序结果写入到一个文件中。
需要注意的是,这个示例中使用了Unicode字符范围`\u1800-\u18AF`来匹配蒙古文字符。如果需要匹配其他语言的单词,可以根据需要修改正则表达式。
相关推荐
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)