Python实现:一键查询文档内容索引的简单程序
lights; who spends himself in a worthy cause; who at the best knows in the end the triumph of high achievement, and who at the worst, if he fails, at least fails while daring greatly, so that his place shall never be with those cold and timid souls who neither know victory nor defeat. 程序使用Python语言编写。 1. 首先,定义一个函数`search_index`,接收两个参数:文档内容和需要查找的内容。 2. 将文档内容拆分成单词列表,使用空格分隔。 3. 创建一个空列表`index_list`,用于存储找到的内容的索引。 4. 遍历文档内容中的每个单词,如果该单词与需要查找的内容匹配,则将其索引加入`index_list`。 5. 返回`index_list`作为结果。 以下是完整代码: ```python def search_index(document, content): words = document.split(' ') index_list = [] for index, word in enumerate(words): if word.lower() == content.lower(): index_list.append(index) return index_list document = "it is not the critic who counts, not the man who points out how the strong man stumbles, the doer of deeds could have done them better. the credit belongs to the man who is actually in the are 'ns, whose face is marred by dust and sweat and blood; who strives valiantly; who errs, and comes short again and again ;because there is not effort without error and shortcoming; but who does actually strive to do the deeds; who knows the great enthusiasms, the great delights; who spends himself in a worthy cause; who at the best knows in the end the triumph of high achievement, and who at the worst, if he fails, at least fails while daring greatly, so that his place shall never be with those cold and timid souls who neither know victory nor defeat." content = input("请输入需要查找的内容:") result = search_index(document, content) if len(result) > 0: print("内容'{}'出现的索引:".format(content)) for index in result: print(index) else: print("未找到要查找的内容。") ``` 运行程序后,会提示输入需要查找的内容,输入后即可获得该内容在文档中出现的索引。如果未找到要查找的内容,程序会给出相应的提示。 ######[AI写代码神器 | 1356点数解答 | 2024-10-24 16:32:26]
- 2025 暑假苍溪 - 广安 - 重庆红色研学:中小学生传承红色基因之旅 (字节豆包 | 1244点数解答 | 2025-06-19 16:32:34)233
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)458
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)343
- DBA必知!MySQL索引、主键、唯一索引与联合索引的区别揭秘(百度文心 | 294点数解答 | 2023-11-09 18:00:37)217
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)414
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)405
- 补全含错误代码:Vue结合Element UI组件实现查询、新增及表格展示功能 ( | 400点数解答 | 2023-12-19 15:20:50)432
- 单线程频繁查ClickHouse致CPU飙升?这些优化方案速看!(DeepSeek | 491点数解答 | 2025-02-13 17:49:54)228
- MySQL:巧用 NOT LIKE 查询字段不包含特定字符串及注意要点 (DeepSeek | 264点数解答 | 2025-02-13 18:25:01)179
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)310
- Python实现简单文档内容查询:精准定位所需内容索引(GPT | 1189点数解答 | 2024-10-21 21:45:05)337
- Python 实现:轻松查询文档中特定内容的所有索引(字节豆包 | 261点数解答 | 2024-10-22 15:37:39)357