当前位置: 首页 > news >正文

python 爬虫技术 第04节 函数和模块

在Python中,函数和模块是组织代码和实现功能复用的重要方式。

Python 函数

函数是一段可重用的代码,用于执行特定任务。在单词管理系统中,函数可以用于处理各种任务,如添加单词、搜索单词、更新单词信息等。

函数定义

使用def关键字定义函数,后跟函数名和括号,括号内可以包含参数。函数体位于冒号后面的缩进代码块中。例如,定义一个函数来添加单词到系统中:

def add_word(word, definition=""):# Check if the word already existsif word in word_database:print(f"The word '{word}' already exists.")else:word_database[word] = {"definition": definition}print(f"The word '{word}' has been added.")
函数调用

调用函数只需使用函数名,后跟括号和必要的参数。例如,调用上面定义的add_word函数:

add_word("hello", "A greeting used to greet someone")
返回值

函数可以通过return语句返回一个值。例如,一个函数可以返回一个单词是否存在:

def word_exists(word):return word in word_database

Python 模块

模块是一个包含定义和语句的单独的Python文件。在单词管理系统中,你可能希望将一些常用功能放在单独的模块中,这样可以使主程序更清晰,同时也便于功能的复用和维护。

创建模块

创建一个名为word_manager.py的文件,里面包含单词管理系统的功能函数。例如:

# word_manager.py
word_database = {}def add_word(word, definition=""):# ... function implementation ...def search_word(word):# ... function implementation ...
导入模块

在其他Python文件中,你可以使用import语句导入模块,并访问其内的函数和变量:

# main.py
import word_managerword_manager.add_word("hello", "A greeting used to greet someone")
result = word_manager.search_word("hello")
print(result)
使用 from…import

你也可以直接从模块中导入特定的函数或变量:

from word_manager import add_word, search_wordadd_word("hello", "A greeting used to greet someone")
search_word("hello")
模块的__name__属性

当模块作为脚本直接运行时,__name__属性会被设置为'__main__'。你可以利用这一点来编写测试代码,仅在直接运行模块时执行:

# word_manager.py
if __name__ == "__main__":print("Running tests...")# Test code goes here

小结

通过使用函数和模块,你可以将单词管理系统的代码组织得更加清晰和模块化,使得代码易于阅读、理解和维护。同时,这也有助于避免代码重复,提高代码的复用性和效率。在实际项目中,你可能会有更多的模块,每个模块负责系统的一个子功能,如用户管理、数据持久化、网络通信等。

让我们通过一个更具体且完整的案例来展示如何在Python中使用函数和模块来构建一个单词管理系统。我们将创建一个模块来封装单词管理的逻辑,并在主程序中使用这些功能。这个例子将展示如何定义和使用函数,以及如何组织代码到模块中。

Step 1: 创建模块 word_database.py

在这个模块中,我们将定义一个字典来存储单词及其相关信息,以及几个函数来处理这些数据。

# word_database.pyword_database = {}def add_word(word, definition=""):"""Adds a word to the word database with an optional definition."""if word.lower() in word_database:print(f"The word '{word}' already exists.")else:word_database[word.lower()] = {"definition": definition}print(f"The word '{word}' has been added.")def search_word(word):"""Searches for a word in the word database and returns its definition."""word = word.lower()if word in word_database:return word_database[word]["definition"]else:return Nonedef update_word(word, new_definition):"""Updates the definition of an existing word in the word database."""word = word.lower()if word in word_database:word_database[word]["definition"] = new_definitionprint(f"The definition of '{word}' has been updated.")else:print(f"The word '{word}' does not exist.")def delete_word(word):"""Deletes a word from the word database."""word = word.lower()if word in word_database:del word_database[word]print(f"The word '{word}' has been deleted.")else:print(f"The word '{word}' does not exist.")

Step 2: 创建主程序 main.py

在这个文件中,我们将导入word_database模块,并使用它的函数来与用户交互。

# main.pyimport word_databasedef main():while True:print("\nWelcome to the Word Database System!")print("1. Add a new word")print("2. Search for a word")print("3. Update a word's definition")print("4. Delete a word")print("5. Exit")choice = input("Please choose an option: ")if choice == '1':word = input("Enter the word you want to add: ")definition = input("Enter the definition: ")word_database.add_word(word, definition)elif choice == '2':word = input("Enter the word you want to search: ")definition = word_database.search_word(word)if definition:print(f"The definition of '{word}': {definition}")else:print(f"The word '{word}' does not exist.")elif choice == '3':word = input("Enter the word you want to update: ")new_definition = input("Enter the new definition: ")word_database.update_word(word, new_definition)elif choice == '4':word = input("Enter the word you want to delete: ")word_database.delete_word(word)elif choice == '5':print("Goodbye!")breakelse:print("Invalid option. Please try again.")if __name__ == '__main__':main()

运行程序

当你运行main.py时,程序会启动一个交互式菜单,允许用户添加、搜索、更新和删除单词。这个例子展示了如何将功能逻辑分离到模块中,并在主程序中使用这些模块,这是大型项目中代码组织的一种常见做法。

通过这种方式,你可以轻松地扩展系统功能,比如增加同义词、反义词的管理,或者将数据存储到文件或数据库中,而不必修改主程序的结构。

为了进一步完善我们的单词管理系统案例,我们可以添加更多的功能和改进,使其成为一个更全面的应用。以下是对之前案例的一些增强和扩展:

Step 1: 扩展 word_database.py 模块

我们将增加同义词和反义词的管理,并提供一个函数来列出所有单词。

# word_database.pyword_database = {}def add_word(word, definition="", synonyms=None, antonyms=None):"""Adds a word to the word database with an optional definition,synonyms, and antonyms."""if word.lower() in word_database:print(f"The word '{word}' already exists.")else:word_database[word.lower()] = {"definition": definition,"synonyms": synonyms or [],"antonyms": antonyms or []}print(f"The word '{word}' has been added.")def search_word(word):"""Searches for a word in the word database and returns its details."""word = word.lower()if word in word_database:return word_database[word]else:return Nonedef update_word(word, new_definition=None, new_synonyms=None, new_antonyms=None):"""Updates the definition, synonyms, or antonyms of an existing word."""word = word.lower()if word in word_database:if new_definition is not None:word_database[word]["definition"] = new_definitionif new_synonyms is not None:word_database[word]["synonyms"] = new_synonymsif new_antonyms is not None:word_database[word]["antonyms"] = new_antonymsprint(f"The word '{word}' has been updated.")else:print(f"The word '{word}' does not exist.")def delete_word(word):"""Deletes a word from the word database."""word = word.lower()if word in word_database:del word_database[word]print(f"The word '{word}' has been deleted.")else:print(f"The word '{word}' does not exist.")def list_words():"""Lists all words in the word database."""for word, details in word_database.items():print(f"{word}: {details['definition']}, Synonyms: {details['synonyms']}, Antonyms: {details['antonyms']}")

Step 2: 更新 main.py

我们将修改主程序,以反映新增加的功能,并改进用户界面。

# main.pyimport word_databasedef main():while True:print("\nWelcome to the Word Database System!")print("1. Add a new word")print("2. Search for a word")print("3. Update a word's details")print("4. Delete a word")print("5. List all words")print("6. Exit")choice = input("Please choose an option: ")if choice == '1':word = input("Enter the word you want to add: ")definition = input("Enter the definition: ")synonyms = input("Enter synonyms (comma-separated): ").split(',')antonyms = input("Enter antonyms (comma-separated): ").split(',')word_database.add_word(word, definition, synonyms, antonyms)elif choice == '2':word = input("Enter the word you want to search: ")details = word_database.search_word(word)if details:print(f"Details of '{word}':\nDefinition: {details['definition']}\nSynonyms: {details['synonyms']}\nAntonyms: {details['antonyms']}")else:print(f"The word '{word}' does not exist.")elif choice == '3':word = input("Enter the word you want to update: ")new_definition = input("Enter the new definition (press Enter to skip): ")new_synonyms = input("Enter new synonyms (comma-separated, press Enter to skip): ").split(',') if input("Do you want to update synonyms? (y/n)").lower() == 'y' else Nonenew_antonyms = input("Enter new antonyms (comma-separated, press Enter to skip): ").split(',') if input("Do you want to update antonyms? (y/n)").lower() == 'y' else Noneword_database.update_word(word, new_definition, new_synonyms, new_antonyms)elif choice == '4':word = input("Enter the word you want to delete: ")word_database.delete_word(word)elif choice == '5':word_database.list_words()elif choice == '6':print("Goodbye!")breakelse:print("Invalid option. Please try again.")if __name__ == '__main__':main()

功能总结

  • 添加单词:用户可以输入单词、定义、同义词和反义词。
  • 搜索单词:显示单词的定义、同义词和反义词。
  • 更新单词:用户可以选择性地更新单词的定义、同义词和/或反义词。
  • 删除单词:从数据库中移除单词。
  • 列出所有单词:显示数据库中所有单词的细节。

通过这些增强,我们的单词管理系统现在提供了更广泛的功能,使用户能够更有效地管理和探索词汇。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 与大数据相关的 Python 第三方库和工具
  • MATLAB基础:数据和变量
  • 基于TensorFlow.js和COCO-SsD模型的实时目标检测网络应用程序
  • Python从0到100(四十六):实现管理员登录及测试功能
  • Vue--解决error:0308010C:digital envelope routines::unsupported
  • CTF ssti零基础(一) 模块注入的payload
  • 【大数据专题】Flink题库
  • unplugin-vue-components 的作用是什么
  • 数据结构——栈(顺序结构)
  • Visual Studio Code + vue快速安装配置Node.js+Vue+webpack+vscode
  • 【Java25】内部类
  • Ubuntu20.04安装Elasticsearch
  • 【STM32 HAL库】ADC
  • 古籍双层PDF制作教程:保姆级古籍数字化教程
  • 掌握互联网路由选择协议:从基础入门到实战
  • CSS相对定位
  • docker python 配置
  • ES6简单总结(搭配简单的讲解和小案例)
  • HTML中设置input等文本框为不可操作
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • node和express搭建代理服务器(源码)
  • October CMS - 快速入门 9 Images And Galleries
  • OSS Web直传 (文件图片)
  • Vue ES6 Jade Scss Webpack Gulp
  • windows下使用nginx调试简介
  • 从伪并行的 Python 多线程说起
  • 两列自适应布局方案整理
  • 如何合理的规划jvm性能调优
  • 如何解决微信端直接跳WAP端
  • 应用生命周期终极 DevOps 工具包
  • 原生JS动态加载JS、CSS文件及代码脚本
  • - 转 Ext2.0 form使用实例
  • ​sqlite3 --- SQLite 数据库 DB-API 2.0 接口模块​
  • #define 用法
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (1)STL算法之遍历容器
  • (附源码)ssm考生评分系统 毕业设计 071114
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (实战)静默dbca安装创建数据库 --参数说明+举例
  • (转)IOS中获取各种文件的目录路径的方法
  • *++p:p先自+,然后*p,最终为3 ++*p:先*p,即arr[0]=1,然后再++,最终为2 *p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1]
  • . Flume面试题
  • .bashrc在哪里,alias妙用
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .Net 8.0 新的变化
  • .net core MVC 通过 Filters 过滤器拦截请求及响应内容
  • .NET Framework 服务实现监控可观测性最佳实践
  • .net反混淆脱壳工具de4dot的使用
  • .sh 的运行
  • @ 代码随想录算法训练营第8周(C语言)|Day57(动态规划)
  • @require_PUTNameError: name ‘require_PUT‘ is not defined 解决方法
  • [ 蓝桥杯Web真题 ]-Markdown 文档解析
  • [Android] Upload package to device fails #2720
  • [BZOJ4566][HAOI2016]找相同字符(SAM)
  • [Codeforces1137D]Cooperative Game