自己设置指定图片位置的代码,chatgpt写的
import os
import random
def get_file_titles(folder_path):
titles = []
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
title = os.path.splitext(filename)[0] # 使用文件名作为标题
titles.append(title)
return titles
def find_matching_keywords(titles, keywords_file):
with open(keywords_file, 'r', encoding='utf-8') as file:
keywords = [line.strip() for line in file]
for title in titles:
matched_keyword = None
for keyword in keywords:
if keyword in title:
matched_keyword = keyword
print(f"有关键词的标题: {title} (关键词: {keyword})")
break
if matched_keyword:
# 生成随机数
random_number = random.randint(1, 5)
# 打开文件进行修改
folder_path = '文本'
file_path = os.path.join(folder_path, title + '.txt')
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read()
# 查找第四个</p>标签的位置
count = 0
index = -1
while count < 4:
index = contents.find('</p>', index + 1)
if index == -1:
break
count += 1
# 在第四个</p>标签之后插入'
modified_contents = contents[:index + len('</p>')] + img_tag + contents[index + len('</p>'):]
print(img_tag,"链接图片添加成功")
print("-----------------------------------------------------------")
# 将修改后的内容写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(modified_contents)
else:
print(f"没有关键词的标题: {title}")
print(f"-----------------------------------------------------------")
folder_path = '文本'
keywords_file = '关键词.txt'
titles = get_file_titles(folder_path)
find_matching_keywords(titles, keywords_file)
import random
def get_file_titles(folder_path):
titles = []
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
title = os.path.splitext(filename)[0] # 使用文件名作为标题
titles.append(title)
return titles
def find_matching_keywords(titles, keywords_file):
with open(keywords_file, 'r', encoding='utf-8') as file:
keywords = [line.strip() for line in file]
for title in titles:
matched_keyword = None
for keyword in keywords:
if keyword in title:
matched_keyword = keyword
print(f"有关键词的标题: {title} (关键词: {keyword})")
break
if matched_keyword:
# 生成随机数
random_number = random.randint(1, 5)
# 打开文件进行修改
folder_path = '文本'
file_path = os.path.join(folder_path, title + '.txt')
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read()
# 查找第四个</p>标签的位置
count = 0
index = -1
while count < 4:
index = contents.find('</p>', index + 1)
if index == -1:
break
count += 1
# 在第四个</p>标签之后插入'
modified_contents = contents[:index + len('</p>')] + img_tag + contents[index + len('</p>'):]
print(img_tag,"链接图片添加成功")
print("-----------------------------------------------------------")
# 将修改后的内容写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(modified_contents)
else:
print(f"没有关键词的标题: {title}")
print(f"-----------------------------------------------------------")
folder_path = '文本'
keywords_file = '关键词.txt'
titles = get_file_titles(folder_path)
find_matching_keywords(titles, keywords_file)