循环遍历文件夹的每个文本文档并且统计每个文档的词频
时间: 2024-05-08 17:19:25 浏览: 9
好的,这个问题很适合我。你可以使用Python程序实现遍历文件夹并统计每个文档的词频。以下是一个示例代码:
```python
import os
from collections import Counter
# 遍历文件夹
folder_path = "your/folder/path/"
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
# 统计词频
with open(os.path.join(folder_path, filename), "r", encoding="utf-8") as f:
word_counts = Counter(f.read().split())
print(f"文件 {filename} 的词频统计结果为:")
print(word_counts)
```
希望这个代码可以帮到你!
相关问题
读取文本数据,并将每个文档转化为词频向量表示。
要读取文本数据,并将每个文档转化为词频向量表示,你可以使用 Python 中的 CountVectorizer 类。这个类可以将一个文本集合转换成一个词频矩阵,每一行表示一个文档,每一列表示一个单词,矩阵中的每个元素表示对应单词在对应文档中出现的次数。
下面是一个简单的例子:
```python
from sklearn.feature_extraction.text import CountVectorizer
# 定义文本集合
corpus = [
"This is the first document.",
"This is the second document.",
"And this is the third one.",
"Is this the first document?",
]
# 创建一个 CountVectorizer 对象
vectorizer = CountVectorizer()
# 将文本集合转换为词频矩阵
X = vectorizer.fit_transform(corpus)
# 输出词频矩阵
print(X.toarray())
# 输出单词列表
print(vectorizer.get_feature_names())
```
输出结果如下:
```
[[1 1 0 0 1 0 1 0]
[1 1 0 0 1 0 0 1]
[0 0 1 1 1 1 0 0]
[1 1 0 0 1 0 1 0]]
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
```
在这个例子中,我们首先定义了一个文本集合,然后创建了一个 CountVectorizer 对象并将文本集合转换为词频矩阵。最后我们输出了词频矩阵和单词列表。你可以根据这个例子来修改你的代码,实现将文档转化为词频向量表示。
帮我写个文本词频统计代码
### 回答1:
吧
嗯,这样吧:
# 导入必要的库
import collections
# 读取文本
with open("text.txt") as f:
text = f.read()
# 统计词频
words = text.split()
counter = collections.Counter(words)
# 打印统计结果
for word, count in counter.most_common():
print(word, count)
### 回答2:
当然可以帮你写一个文本词频统计的代码。下面是一个简单的Python代码示例:
```python
def word_freq(text):
words = text.split() # 将文本拆分成单词列表
freq = {} # 用字典存储每个单词的频率
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
return freq
text = input("请输入文本:")
result = word_freq(text)
print("词频统计结果:")
for word, freq in result.items():
print(f"{word}: {freq}")
```
这个代码定义了一个`word_freq`函数,它接受一个字符串类型的文本作为参数,并返回一个字典,其中包含了每个单词及其对应的词频。
代码首先使用`split`方法将文本拆分成单词列表。然后通过遍历单词列表,对每个单词进行词频统计。使用字典`freq`来存储每个单词的频率,如果某个单词已经在字典中存在,就将其频率加1;如果不存在,就将其初始频率设为1。
最后,打印出词频统计的结果,遍历字典中的每个键值对,输出对应的单词及其频率。
你只需运行这段代码并输入你想要进行词频统计的文本,它会给出每个单词的词频统计结果。