import streamlit as st import requests import jieba # 设置API Key API_KEY = 'YOUR_API_KEY' # 定义抽取函数 def extract_relation(sentence): url = 'https://aip.baidubce.com/rpc/2.0/kg/v1/cognitive/entity_annotation' header = { 'content-type': 'application/json', 'charset': 'UTF-8' } # 构建请求体 data = { 'data': sentence, 'mode': 1 } # 发送请求 response = requests.post(url, headers=header, json=data, auth=('apikey', API_KEY)) if response.status_code == 200: result = response.json() if 'items' in result: relations = [] for item in result['items']: if 'kg' in item: relation = item['kg']['relation'] relations.append(relation) return relations return [] # Streamlit界面 def main(): st.title('关系抽取') sentence = st.text_input('请输入要抽取关系的句子:') if sentence: # 分词 words = jieba.cut(sentence) words = [word for word in words if len(word) > 1] # 把关系抽取结果展示在界面上 relations = extract_relation(''.join(words)) if len(relations) > 0: res_str = ', '.join(relations) st.success(f'关系抽取结果:{res_str}') else: st.warning('未能抽取到关系') if __name__ == '__main__': main()请将两个函数合并成一个函数
时间: 2024-02-15 08:26:58 浏览: 112
Request_API_SpaceX:https
好的,这里是将两个函数合并的代码:
```python
import streamlit as st
import requests
import jieba
# 设置API Key
API_KEY = 'YOUR_API_KEY'
# Streamlit界面和抽取函数合并
def main():
st.title('关系抽取')
sentence = st.text_input('请输入要抽取关系的句子:')
if sentence:
# 构建请求体
url = 'https://aip.baidubce.com/rpc/2.0/kg/v1/cognitive/entity_annotation'
header = {
'content-type': 'application/json',
'charset': 'UTF-8'
}
data = {
'data': sentence,
'mode': 1
}
# 发送请求
response = requests.post(url, headers=header, json=data, auth=('apikey', API_KEY))
if response.status_code == 200:
result = response.json()
if 'items' in result:
relations = []
# 分词
words = jieba.cut(sentence)
words = [word for word in words if len(word) > 1]
# 抽取关系
for item in result['items']:
if 'kg' in item:
relation = item['kg']['relation']
relations.append(relation)
# 把关系抽取结果展示在界面上
if len(relations) > 0:
res_str = ', '.join(relations)
st.success(f'关系抽取结果:{res_str}')
else:
st.warning('未能抽取到关系')
if __name__ == '__main__':
main()
```
在这个代码中,`main()` 函数里面包含了原来的 Streamlit 界面和抽取函数的代码。首先用户输入要抽取关系的句子,然后构建请求体,并使用 requests 发送请求。如果请求成功,就从返回结果中抽取关系,并将结果展示在 Streamlit 界面上。
阅读全文