遍历“C:\Users\84297\Desktop\爬虫\data”路径中的txt文件并进行分词的代码怎么写
时间: 2023-03-29 09:04:28 浏览: 52
你可以使用Python中的os和jieba库来实现这个功能。具体代码如下:
```python
import os
import jieba
# 遍历指定路径下的所有txt文件
def traverse_folder(path):
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 对文件内容进行分词
seg_list = jieba.cut(content)
print('/'.join(seg_list))
# 调用函数进行遍历和分词
traverse_folder(r'C:\Users\84297\Desktop\爬虫\data')
```
这段代码会遍历指定路径下的所有txt文件,并对文件内容进行分词,最后输出分词结果。
相关问题
遍历“C:\Users\84297\Desktop\爬虫\data”路径中的txt文件进行分词并生成对应的新文本文件的代码如何编写
你可以使用Python中的os和jieba库来实现这个功能。首先,你需要导入这两个库:
import os
import jieba
然后,你可以使用os库中的walk函数来遍历指定路径下的所有txt文件:
for root, dirs, files in os.walk("C:/Users/84297/Desktop/爬虫/data"):
for file in files:
if file.endswith(".txt"):
# 对txt文件进行分词并生成新文件
接下来,你需要打开每个txt文件并对其进行分词。你可以使用jieba库中的cut函数来实现分词:
with open(os.path.join(root, file), "r", encoding="utf-8") as f:
content = f.read()
words = jieba.cut(content)
最后,你需要将分词结果写入新的文本文件中:
with open(os.path.join(root, "new_" + file), "w", encoding="utf-8") as f:
f.write(" ".join(words))
完整的代码如下:
import os
import jieba
for root, dirs, files in os.walk("C:/Users/84297/Desktop/爬虫/data"):
for file in files:
if file.endswith(".txt"):
with open(os.path.join(root, file), "r", encoding="utf-8") as f:
content = f.read()
words = jieba.cut(content)
with open(os.path.join(root, "new_" + file), "w", encoding="utf-8") as f:
f.write(" ".join(words))
遍历“C:\Users\84297\Desktop\爬虫\data”路径中的txt文件
你可以使用以下代码来遍历指定路径中的txt文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
char *path = "C:\\Users\\84297\\Desktop\\爬虫\\data";
if ((dir = opendir(path)) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (strstr(ent->d_name, ".txt") != NULL) {
printf("%s\n", ent->d_name);
}
}
closedir(dir);
} else {
printf("无法打开目录\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}