LCA_LLM_application/Retrieval_new/utils.py

134 lines
3.9 KiB
Python
Raw Normal View History

2025-03-19 21:02:49 +08:00
import nltk
from nltk.tokenize import word_tokenize
from nltk import pos_tag
import jieba.posseg as pseg
2025-03-21 16:09:46 +08:00
# # 下载相关数据
# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')
2025-03-19 21:02:49 +08:00
from nltk.stem import WordNetLemmatizer
import string
import re
2025-03-21 16:09:46 +08:00
from langchain.prompts import ChatPromptTemplate
from langchain.schema import SystemMessage, HumanMessage
from langchain_openai import ChatOpenAI
2025-03-19 21:02:49 +08:00
def preprocess_eng(text):
'''
英文文本预处理小写化去除标点待定去除特殊符号只保留单词
拼写是否正确因为是从ecoinvent导入的没有拼写错误
词干提取(stemming)和词形还原(lemmatization)可以处理一下有的提取不准确不做此操作
'''
# 去除标点
text = text.translate(str.maketrans('', '', string.punctuation))
# 去除数字
text = re.sub(r'\d+', ' ', text)
# 去除多余字符
text = re.sub(r'[^A-Za-z0-9\s]', '', text)
# 去除多余空格
text = re.sub(r'\s+', ' ', text)
return text
def preprocess_zh(text):
'''
中文文本预处理:只保留中文内容去除英文数字和标点
'''
text = str(text)
# 去除英文
text = re.sub(r'[a-zA-Z]',' ',text)
text = re.sub(r'\d', ' ', text)
# 去除中文标点符号
text = re.sub(r'[,。!?、;:“”()《》【】-]', ' ', text)
# 去除英文标点符号
text = re.sub(r'[.,!?;:"\'\(\)\[\]{}]', ' ', text)
# 去除空格
text = re.sub(r'\s+','',text)
return text
# 英文名词处理
def get_noun_en(text):
# 分词
words = word_tokenize(text)
# 词性标注
tagged = pos_tag(words)
# 提取名词
nouns = [word for word, tag in tagged if tag.startswith('NN')]
noun = ' '.join(nouns)
return noun
# 中文名词提取
def get_noun_zh(text):
x = str(text)
if x=='nan':
return ''
words = pseg.cut(text)
nouns = [word for word, flag in words if flag.startswith('n')]
noun = ' '.join(nouns)
return noun
def has_no_chinese(text):
"""
判断一个文本是否不包含中文字符
参数:
text (str): 需要检查的文本
返回:
bool: 如果文本中没有中文字符返回True否则返回False
"""
for char in text:
if '\u4e00' <= char <= '\u9fff' or \
'\u3400' <= char <= '\u4dbf' or \
'\u2f00' <= char <= '\u2fdf' or \
'\u3100' <= char <= '\u312f' or \
'\u31a0' <= char <= '\u31bf':
return False
2025-03-21 16:09:46 +08:00
return True
def extract_List(text):
pattern = r'\[(.*?)\]'
matches = re.findall(pattern,text)
try:
return matches[-1]
except Exception as e:
print("字符串处理异常!",e)
return None
def translate(query):
sys_template = '''
你是一个专注于化工环境学科领域的翻译专家
用户将提供一个生命周期评价领域数据库的查询查询可能包含中英文字符你的任务是
1. 将查询中的所有英文表述转化为对应的中文表述
2. 确保转化后的查询中不含任何非中文语言
3. 将完整的中文查询以[]格式返回
4. 不返回除[]格式外的任何其他内容
请严格按照上述要求执行
'''
human_template = "查询内容为:{context}"
chat_prompt = ChatPromptTemplate.from_messages([
("system", sys_template),
("human", human_template)
])
messages = chat_prompt.format_messages(context=query)
# print(messages)
llm = ChatOpenAI(
model = "deepseek-chat",
base_url="https://api.deepseek.com",
api_key="sk-3e42e538bc39411ab80761106d83dda9",
temperature=0,
)
response = llm.invoke(messages)
content = response.content
result = extract_List(content)
return result
if __name__ == '__main__':
res = translate("HCOOH的定义是什么")
print(res)