使用AnilistPython开发动漫搜索:解决换行符与输出对齐问题
问题解决:AnilistPython动漫搜索的Plot清理与输出对齐
问题说明
使用AnilistPython开发动漫搜索功能时,遇到两个问题:
- Plot字段包含换行符、
<br>标签和空内容,无法生成连贯文本 - 输出的各项信息无法对齐,格式杂乱
修改后的代码
from AnilistPython import Anilist import re # 初始化Anilist客户端 anilist = Anilist() # 用户输入并获取动漫信息 ani_search = anilist.get_anime(input('Enter the Anime Name\t:\t'), manual_select=True) df = ani_search # 处理Genres,直接拼接成字符串 cate1 = ' , '.join(df['genres']) # 处理剧集状态与数量 if df['airing_status'] == 'RELEASING': x = 'Ongoing' y1 = df['next_airing_ep']['episode'] elif df['airing_status'] == 'FINISHED': x = 'Ended' y1 = df['airing_episodes'] else: x = 'None' y1 = 'N/A' # 清理Plot内容:移除<br>、换行符,合并多余空格 clean_plot = re.sub(r'<br>|\n', ' ', df['desc']) clean_plot = re.sub(r'\s+', ' ', clean_plot).strip() # 格式化输出,确保对齐 print(f"\n{'Title_Name':<15} : {df['name_english']}") print(f"{'Romji_Title':<15} : {df['name_romaji']}") print(f"{'Plot':<15} : {clean_plot}") print(f"{'Airing_Format':<15} : {df['airing_format']}") print(f"{'Status':<15} : {x}") print(f"{'Episodes_Count':<15} : {y1}") print(f"{'Genres':<15} : {cate1}") print(f"{'Rating':<15} : {df['average_score']}/100\n")
关键修改点
Plot内容清理:
- 用
re.sub(r'<br>|\n', ' ', df['desc'])替换<br>标签和换行符为空格 - 再用
re.sub(r'\s+', ' ', clean_plot).strip()合并连续空格并移除首尾多余空格,得到连贯的文本
- 用
输出对齐处理:
- 使用
{key:<15}的格式化语法,让每个标签左对齐并占用15个字符宽度,确保冒号位置统一,输出规整
- 使用
简化Genres处理:
- 直接用
' , '.join(df['genres'])生成分类字符串,无需循环拼接,代码更简洁
- 直接用
最终输出效果
Enter the Anime Name : Bleach 1. BLEACH 2. BEACH 3. Akkanbee da Please select the anime that you are searching for in number: 1 Title_Name : Bleach Romji_Title : BLEACH Plot : Ichigo Kurosaki is a rather normal high school student apart from the fact he has the ability to see ghosts. This ability never impacted his life in a major way until the day he encounters the Shinigami Kuchiki Rukia, who saves him and his family's lives from a Hollow, a corrupt spirit that devours human souls. Wounded during the fight against the Hollow, Rukia chooses the only option available to defeat the monster and passes her Shinigami powers to Ichigo. Now forced to act as a substitute until Rukia recovers, Ichigo hunts down the Hollows that plague his town. Airing_Format : TV Status : Ended Episodes_Count : 366 Genres : Action , Adventure , Supernatural Rating : 76/100
内容的提问来源于stack exchange,提问作者naoki
相关产品推荐
相关产品推荐

