poem_recitation / app.py
ahalamora's picture
Upload app.py
e55c175
import streamlit as st
import string
import random
def cover_some_text(text, replacement_prob):
result = ""
for char in text:
if char in string.punctuation + ',。!?;:‘’“”【】《》、': # 包含中文标点
result += char
elif char == '\n': # 保留换行符
result += char
else:
if random.random() <= replacement_prob:
result += '囗'
else:
result += char
return result
def cover_text_and_keep_first_word(text):
punctuations = string.punctuation + ',。!?;:‘’“”【】《》、'
result = ""
pre_char = '。'
for char in text:
if pre_char in punctuations: # 包含中文标点
result += char
elif pre_char == '\n': # 保留换行符
result += char
elif char in punctuations:
result += char
elif char == '\n': # 保留换行符
result += char
else:
result += '囗'
pre_char = char
return result
st.title('初中古诗词背诵APP 📖')
with open('poems.txt') as f:
data = f.read()
data = data.split('\n\n')
poems = {}
for poem in data:
poem = poem.split('\n')
id = int(poem[0])
name = poem[1]
poet = poem[2]
content = '\n\n'.join(poem[3:])
poems[name] = {
'id': id,
'name': name,
'poet': poet,
'content': content
}
# 写一个下拉菜单
poem_name = st.selectbox('选择要背诵的诗词', poems.keys())
with st.sidebar:
recitation_mode = st.radio('模式', [
'显示全文',
'按比例遮盖',
'只显示句首字'
])
if recitation_mode == '按比例遮盖':
replacement_prob = st.slider('遮盖占比', 0.0, 1.0, 0.8, 0.1)
if recitation_mode == '显示全文':
st.markdown(f'### {poems[poem_name]["name"]}')
st.markdown(f'#### {poems[poem_name]["poet"]}')
st.markdown(f'{poems[poem_name]["content"]}')
elif recitation_mode == '按比例遮盖':
st.markdown(f'### {poems[poem_name]["name"]}')
st.markdown(f'#### {poems[poem_name]["poet"]}')
st.markdown(f'{cover_some_text(poems[poem_name]["content"], replacement_prob)}')
elif recitation_mode == '只显示句首字':
st.markdown(f'### {poems[poem_name]["name"]}')
st.markdown(f'#### {poems[poem_name]["poet"]}')
st.markdown(f'{cover_text_and_keep_first_word(poems[poem_name]["content"])}')
else:
pass