背景:
文笔不够,技术来凑。其实应该配合爬虫,把文章爬到本地,再批量分析,效果会更好。但是代理ip要钱,之前免费站点没了。所以先做了一个简陋版。
目录结构:

代码:
import re
import copy
import os
# ================================ 变量 ============================================
"""
公共变量
"""
#文件夹目录
path = "./doc"
#得到文件夹下的所有文件名称
files= os.listdir(path)
#key(按下面的分组,对应的关键字去收集)
keyList = [
['眼','眸','瞳','眼底'],
['嘴','唇'],
['眉'],
['脸颊']
]
#变量存储
# eye = []
# mouth = []
result =[];
resultList = [[] for i in range(len(keyList))];
# ================================ 函数 ============================================
"""
返回删除所有空值后的arr
"""
def get_real_arr(arr):
arr_copy = copy.deepcopy(arr)
arr_copy = list(filter(None, arr_copy))
while '' in arr_copy:
arr_copy.remove('')
return arr_copy
"""
遍历文件,过滤字符
"""
def getAllList(position):
#用于存储当前文件的所有的断句
matrix = []
with open(position, encoding='utf-8') as f:
for line in f.readlines():
line = line.strip('\n') # 去掉列表中每一个元素的换行符
line = line.strip();
#清空对话等标点符号
line = re.sub(r"[:“”]", "", line);
#根据标点去断句,逗号区域不断句
a = re.split('[.。::!!??]', line)
# 清除数组中的空字符
a = get_real_arr(a);
# 合并数组(当前文件的所有的断句)
matrix.extend(a);
#筛选符合条件的
for each in matrix:
# print(each, len(matrix))
for index,key in enumerate(keyList):
for type in key:
if type in each:
resultList[index].append(each);
continue
"""
初始化
"""
def init():
"""
获取所有txt,并遍历
"""
for file in files: # 遍历文件夹
position = path + '\\' + file # 构造绝对路径,"\\",其中一个'\'为转义符
print(position)
getAllList(position)
"""
打印
"""
with open('data.txt', 'w', encoding='utf-8') as f: # 设置文件对象
for index,word in enumerate(resultList):
print(keyList[index]);
print('\n'.join(word));
f.write("\n【"+','.join(keyList[index])+"】\n")
f.write('\n'.join(word))
f.write('\n\n')
# ================================ 初始化 ============================================
init();
生成效果:

1万+



被折叠的 条评论
为什么被折叠?



