实用的common.utils函数整理,助力Python项目开发
在Python项目开发中,常常会用到一些实用的工具函数来简化代码、提高开发效率。本文整理了一些常用的工具函数,并提供了使用例子,帮助读者更好地理解和应用这些函数。
1. 字符串处理工具
1.1 split_by_whitespace(string: str) -> List[str]: 将字符串按空格分割成列表。
>>> split_by_whitespace("Hello world")
['Hello', 'world']
1.2 remove_punctuation(string: str) -> str: 去除字符串中的标点符号。
>>> remove_punctuation("Hello, world!")
'Hello world'
1.3 remove_whitespace(string: str) -> str: 去除字符串中的空格和换行符。
>>> remove_whitespace("Hello
world")
'Helloworld'
2. 文件处理工具
2.1 create_directory(directory: str) -> None: 创建目录。
>>> create_directory("mydir")
2.2 delete_directory(directory: str) -> None: 删除目录及其下所有文件和子目录。
>>> delete_directory("mydir")
2.3 copy_file(source_file: str, destination_file: str) -> None: 复制文件。
>>> copy_file("source.txt", "destination.txt")
3. 时间处理工具
3.1 current_timestamp() -> int: 获取当前时间的时间戳。
>>> current_timestamp() 1622123763
3.2 timestamp_to_datetime(timestamp: int) -> datetime.datetime: 将时间戳转换为日期时间对象。
>>> timestamp_to_datetime(1622123763) datetime.datetime(2021, 5, 27, 10, 22, 43)
4. 数据处理工具
4.1 flatten_list(nested_list: List) -> List: 将嵌套的列表扁平化。
>>> flatten_list([[1, 2], [3, 4], [5, 6]]) [1, 2, 3, 4, 5, 6]
4.2 unique_elements(sequence: Sequence) -> List: 获取序列中的 元素。
>>> unique_elements([1, 2, 3, 2, 1]) [1, 2, 3]
4.3 count_elements(sequence: Sequence) -> Dict: 统计序列中各元素的出现次数。
>>> count_elements([1, 2, 3, 2, 1])
{1: 2, 2: 2, 3: 1}
5. HTTP请求工具
5.1 send_get_request(url: str, params: Dict[str, Any] = None) -> Any: 发送GET请求并返回响应结果。
>>> response = send_get_request("https://api.example.com/users", params={"page": 1, "limit": 10})
>>> print(response)
{'total': 100, 'users': [...]}
5.2 send_post_request(url: str, data: Dict[str, Any] = None) -> Any: 发送POST请求并返回响应结果。
>>> response = send_post_request("https://api.example.com/users", data={"name": "John", "age": 25})
>>> print(response)
{'id': 123, 'name': 'John', 'age': 25}
以上只是一些常用的工具函数示例,实际开发中可能需要根据具体需求自定义更多的工具函数。通过使用这些函数,可以极大地提高Python项目开发的效率和代码质量。
