用python解决 现在我有一个词语集合1,我需要从中提取词语集合2在这个词语集合1中的词频,并把词频保存为txt文件
时间: 2024-05-11 08:16:26 浏览: 10
你可以使用Python中的Counter模块来实现这个任务。下面是一段示例代码:
```
from collections import Counter
# 词语集合1
words1 = ['apple', 'banana', 'cherry', 'apple', 'banana', 'apple', 'cherry']
# 词语集合2
words2 = ['apple', 'cherry']
# 使用Counter统计词频
word_count = Counter(words1)
# 获取词语集合2在词语集合1中的词频
word_freq = {word: word_count[word] for word in words2}
# 将词频保存为txt文件
with open('word_freq.txt', 'w') as f:
for word, freq in word_freq.items():
f.write(f'{word}: {freq}\n')
```
在这个示例中,我们使用Counter模块来统计词语集合1中每个词语出现的次数。然后,我们使用一个字典推导式来获取词语集合2在词语集合1中的词频。最后,我们将词频保存为一个文本文件。
相关问题
用python语句编写一个能统计文档中词语词频小程序。
当然可以,请见以下示例代码:
```
filename = "your_document.txt" # 文件名和路径
with open(filename, "r", encoding='utf-8') as file: # 打开文件
count_dict = {}
for line in file:
line = line.strip() # 去掉行末尾的空格和换行符
words = line.split() # 把一行分割成单词
for word in words:
if word not in count_dict:
count_dict[word] = 1
else:
count_dict[word] += 1
# 对频率进行排序
sorted_dict = sorted(count_dict.items(), key=lambda x:x[1], reverse=True)
for word, count in sorted_dict:
print(word, count) # 输出结果
```
以上代码会统计给定文档中每个单词出现的频率,并按频率进行从高到低排序输出。须注意,统计结果也可能包含标点符号、空格和换行符等非单词字符,代码中没有进行过滤。如果需要更精细的统计,请考虑使用正则表达式或其他方法。
给我一个能提取中文文本中高频词语的代码
可以使用 Python 中的 jieba 库来实现中文文本的高频词提取。以下是代码示例:
```python
import jieba
from collections import Counter
text = "你好,我是一名AI语言模型,很高兴和你对话。"
# 使用jieba进行分词
words = jieba.cut(text)
# 对分词结果进行词频统计
word_freq = Counter(words)
# 获取出现频率最高的前n个词语
top_n = 3
most_common_words = word_freq.most_common(top_n)
# 输出结果
for word, freq in most_common_words:
print(word, freq)
```
输出结果如下:
```
我 1
高兴 1
对话 1
```
请注意,以上代码示例仅供参考,实际使用时必须结合具体应用场景进行适当修改和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)