Effective Python系列(1.2):尽量使用f-string替代其它的字符串格式化

部署运行你感兴趣的模型镜像

在 Python 语言当中,格式化字符串的常用方法有以下几种:

  1. % 格式化,类似于 C 语言当中的格式化方法。
  2. str.format() 方法。
  3. f-string 格式化字符串字面量。

下面先来回顾这几种常用方法的用法。

1.1 % 格式化

示例:


name = "Alice"
age = 30
greeting = "Hello, %s! You are %d years old." % (name, age)
print(greeting)

此种方法的缺点:

  1. %右侧那个元组里面的值在类型或顺序发生变化时,那么程序可能会因为转换类型时发生
    不兼容问题而出现错误。

    key = 'var'
    value = 1.234
    formatted = '%-10s = %.2f' % (key, value)
    print(formatted)
    
  2. 在填充格式化字符串模板之前,经常需要对填进去的值做一些处理,但这样一来,
    整个表达式就会变得很长,难以阅读。

    pantry = {("apple", 8), ("orange", 10), ("banana", 3)}
    for i, (item, count) in enumerate(pantry):
        print("#%d: %-10s = %d" % (i+1, item, round(count)))
    
    
  3. 如果想用同一个值来填充格式字符串里的多个位置,那么必须在%操作符右侧的元组中相应地多次重复该值。

    template = '%s loves food. See %s cook.'
    name = 'Max'
    formatted = template % (name, name)
    print(formatted)
    
  4. dict写到格式化表达式里面会让代码变多。每个键都至少要写两次:
    一次是在格式说明符中,还有一次是在字典中作为键。
    另外,定义字典的时候,可能还要专门用一个变量来表示这个键所对应的值,
    而且这个变量的名称或许也和键名相同,这样算下来就是三次了。

    soup = 'lentil'
    formatted = 'Today\'s soup is %(soup)s.' % {'soup': soup}
    print(formatted)
    

1.2 str.format()方法

str.format() 是 Python 2.7 和 3.0 引入的格式化方法,它更强大和灵活,支持位置参数、关键字参数等。

  1. 使用位置参数
greeting = "Hello, {0}! You are {1} years old.".format(name, age) 
print(greeting)
  1. 使用关键字参数
greeting = "Hello, {name}! You are {age} years old.".format(name="Charlie", age=28)
print(greeting)

# 输出
# Hello, Charlie! You are 28 years old.
  1. 格式化数值
pi = 3.14159
formatted = "Pi is approximately {:.2f}".format(pi)  # 保留两位小数
print(formatted)
# 输出:Pi is approximately 3.14

str.format() 无法解决 C 风格格式化字符串的第二和第四个问题。

1.3 f-string

f-strings 是 Python 3.6 引入的格式化方法,它使得格式化更加简洁和易读。通过在字符串前加上 fF,可以直接在字符串中嵌入表达式。

  1. 语法:
f"格式字符串 {表达式}"

示例:

name = "Eve"
age = 35
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)

输出:

Hello, Eve! You are 35 years old.
  1. 支持复杂表达式:
a = 5
b = 3
result = f"The sum of {a} and {b} is {a + b}."
print(result)

输出:

The sum of 5 and 3 is 8.
  1. 格式化数值:
pi = 3.14159
formatted = f"Pi is approximately {pi:.2f}"  # 保留两位小数
print(formatted)

输出:

Pi is approximately 3.14

建议:在 Python 程序当中,尽量使用 f-string 格式化字符串。

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

# C/C++ 项目考核:简易文件内容统计工具 ## 一、项目背景与目标 日常学习中,我们经常需要统计文本文件的基本信息(如行数、单词数)。本项目要求开发一个 “简易文件内容统计工具”,以**C/C++ 为核心**实现文件分析,用 Python 生成简单可视化图表(比如词云),通过 CMake 完成编译构建。 项目旨在考验基础能力: 1. C/C++ 核心语法:变量、函数、数组 / 容器、文件 IO、字符串处理; 2. STL 基础应用:`std::vector`/`std::map`的简单使用; 3.语言配合:C/C++ 输出统计结果到文本文件,Python 读取并绘图; 4. 工程基础:CMake 基本配置(单文件 / 多文件编译)、命令行参数使用。 ## 二、技术栈要求 | 技术模块 | 核心工具 / 库 | 关键知识点 | | -------- | ----------------------- | --------------------------------------- | | 核心逻辑 | C/C++11 及以上 | 文件读取、字符串分割、基础统计 | | 数据存储 | 文本文件(.txt) | 结构化数据写入(如每行一个统计项) | | 可视化 | Python 3.x + matplotlib | 读取文本文件、绘制简单柱状图 | | 构建工具 | CMake 3.10+ | 定义可执行目标、指定 C++ 标准、编译命令 | ## 三、项目功能需求 ### 3.1 核心功能(必做) 1. **C/C++ 统计模块**: - 读取用户通过命令行指定的文本文件(如`input.txt`),支持英文文本即可; - 实现 3 类基础统计: - 总行数(空行不计入,空行定义:仅含空格 / 换行符的行); - 总单词数(以空格 / 标点`!,.?;:`分割,如 “hello,”“hello!” 均算 “hello”); - 高频单词 Top5(仅统计出现次数≥2 的单词,忽略大小写,如 “Hello” 和 “hello” 视为同一单词); - 将统计结果写入result.txt,格式示例: ```plaintext 总行数:15 总单词数:280 高频单词Top5: hello 8次 world 5次 cpp 4次 python 3次 code 2次 ``` 2. **Python 可视化模块**: - 读取`result.txt`中的 “高频单词 Top5” 数据; - 用`matplotlib`绘制柱状图(横轴为单词,纵轴为次数),保存为`top5.png`; - 图表要求:包含标题(如 “高频单词统计”)、横轴标签(“单词”)、纵轴标签(“出现次数”)。 3. **CMake 构建模块**: - 编写CMakeLists.txt,实现: - 指定 C++ 标准为 C++11- 将 C++ 代码编译为可执行文件(名称建议为`file_stat`); - 编译后可通过命令行运行:`./file_stat input.txt`(Linux/macOS)或`file_stat.exe input.txt`(Windows); - 提供`README.md`,说明编译步骤(如 “mkdir build && cd build && cmake .. && make”)和运行方法。 ### 3.2 扩展功能(选做) 1. C++ 模块: - 支持命令行参数指定输出文件路径(如`./file_stat input.txt --output my_result.txt`); - 新增统计:文本中所有中文字符的总出现次数。 2. Python 模块: - 柱状图中为每个柱子设置不同颜色(如用`['red', 'green', 'blue', 'yellow', 'purple']`)。 3. 构建优化: - 用 CMake 定义 “run” 目标,执行`make run`(Linux/macOS)或`cmake --build . --target run`(Windows)时,自动运行 C++ 程序(默认读取`test.txt`)并调用 Python 脚本生成图表。 ## 四、实现提示 1. **C++ 文件读取**: - 用`std::ifstream`打开文件,`getline()`逐行读取,通过判断行是否为空统计有效行数; - 单词分割:遍历每行字符,遇到空格或标点时,将之前的字符拼接为单词,用`tolower()`统一转为小写后存入`std::map<std::string, int>`计数。 2. **高频词排序**: - 用`std::map`统计完单词次数后,转为`std::vector`(存储`pair<单词, 次数>`),再用`std::sort`排序,取前 5 个次数≥2 的单词。 3. **Python 绘图**: - 读取`result.txt`:用`open()`打开文件,遍历行找到 “高频单词 Top5:” 后的内容,按行分割提取单词和次数; - 绘图示例代码: ```python import matplotlib.pyplot as plt # 假设提取的数据为: words = ["hello", "world", "cpp", "python", "code"] counts = [8, 5, 4, 3, 2] plt.bar(words, counts) plt.title("高频单词统计") plt.xlabel("单词") plt.ylabel("出现次数") plt.savefig("top5.png") ``` 4. **CMake 基础配置示例**: ```cmake cmake_minimum_required(VERSION 3.10) project(FileStatTool) # 项目名称 set(CMAKE_CXX_STANDARD 11) # 指定C++11标准 add_executable(file_stat main.cpp) # 编译main.cpp为file_stat可执行文件 ``` ## 五、提交要求 1. 源代码: - C++ 代码(如`main.cpp`,若分模块可拆分为`statistic.cpp`+`statistic.h`等); - Python 脚本(如`plot.py`); - `CMakeLists.txt`; - 测试文本`test.txt`(自行准备,建议 100-500 单词)。 2. 运行结果: - 生成的`result.txt`; - 生成的`top5.png`。 3. 文档: - `README.md`:包含编译步骤、运行命令、功能说明、实现过程中遇到的问题及解决方法(至少 1 个问题)。 ## 六、难度说明 - 核心功能仅涉及 C++ 基础语法(循环、条件判断)、STL 入门(map 存储键值对、vector 排序)、文件 IO(读写文本),逻辑简单易实现; - Python 部分无需复杂数据处理,仅需基础文件读取和 matplotlib 调用(可直接参考示例代码修改); - CMake 配置简化,无需依赖外部库,3-5 行核心代码即可完成编译配置,降低工程化门槛。 我是一个新手小白帮我列出我需要做的操作并详细给出所需的代码及各种东西
11-16
# 项目操作指南与完整代码实现 ## 题目重述 开发一个简易文件内容统计工具,使用 C++ 统计文本文件的行数、单词数和高频词,并将结果写入 `result.txt`;再用 Python 读取该文件并绘制柱状图;通过 CMake 构建整个项目。 --- ## 详解 ### 1. 文件结构规划 创建以下目录结构: ``` file_stat_project/ ├── CMakeLists.txt ├── main.cpp ├── plot.py ├── test.txt ├── result.txt (自动生成) └── top5.png (自动生成) ``` --- ### 2. C++ 核心代码(main.cpp) ```cpp #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <cctype> #include <algorithm> #include <sstream> // 将字符串转为小写 std::string toLower(const std::string& str) { std::string result = str; for (char& c : result) { c = std::tolower(c); } return result; } // 判断是否为空行(仅空格或制表符) bool isEmptyLine(const std::string& line) { for (char c : line) { if (c != ' ' && c != '\t' && c != '\r') return false; } return true; } // 提取单词(去除标点) std::vector<std::string> extractWords(const std::string& line) { std::vector<std::string> words; std::string word; for (char c : line) { if (std::isalpha(c)) { word += std::tolower(c); } else { if (!word.empty()) { words.push_back(word); word.clear(); } } } if (!word.empty()) { words.push_back(word); } return words; } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "用法: " << argv[0] << " <输入文件路径>" << std::endl; return 1; } std::string input_file = argv[1]; std::ifstream infile(input_file); if (!infile.is_open()) { std::cerr << "错误:无法打开文件 " << input_file << std::endl; return 1; } int line_count = 0; int word_count = 0; std::map<std::string, int> word_freq; std::string line; while (std::getline(infile, line)) { if (isEmptyLine(line)) continue; line_count++; auto words = extractWords(line); word_count += words.size(); for (const auto& word : words) { word_freq[word]++; } } infile.close(); // 获取Top5高频词(出现次数≥2) std::vector<std::pair<std::string, int>> top_words; for (const auto& pair : word_freq) { if (pair.second >= 2) { top_words.push_back(pair); } } // 按频次降序排序 std::sort(top_words.begin(), top_words.end(), [](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) { return a.second > b.second; }); // 只保留前5个 if (top_words.size() > 5) { top_words.resize(5); } // 写入 result.txt std::ofstream outfile("result.txt"); if (!outfile.is_open()) { std::cerr << "错误:无法创建 result.txt" << std::endl; return 1; } outfile << "总行数:" << line_count << std::endl; outfile << "总单词数:" << word_count << std::endl; outfile << "高频单词Top5:" << std::endl; for (const auto& pair : top_words) { outfile << pair.first << " " << pair.second << "次" << std::endl; } outfile.close(); std::cout << "统计完成!结果已保存至 result.txt" << std::endl; return 0; } ``` --- ### 3. Python 可视化脚本(plot.py) ```python import matplotlib.pyplot as plt def read_top5_from_result(): words = [] counts = [] try: with open('result.txt', 'r', encoding='utf-8') as f: lines = f.readlines() found = False for line in lines: if "高频单词Top5:" in line: found = True continue if found and line.strip() and "次" in line: parts = line.split() if len(parts) == 2: word = parts[0] count = int(parts[1].replace("次", "")) words.append(word) counts.append(count) if len(words) >= 5: break except Exception as e: print(f"读取 result.txt 失败: {e}") return [], [] return words, counts words, counts = read_top5_from_result() if words and counts: colors = ['red', 'green', 'blue', 'yellow', 'purple'] plt.figure(figsize=(10, 6)) bars = plt.bar(words, counts, color=colors[:len(words)]) plt.title("高频单词统计") plt.xlabel("单词") plt.ylabel("出现次数") plt.xticks(rotation=45) for bar, count in zip(bars, counts): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.1, str(count), ha='center', va='bottom') plt.tight_layout() plt.savefig("top5.png") print("图表已保存为 top5.png") else: print("未找到有效的Top5数据") ``` --- ### 4. CMake 配置文件(CMakeLists.txt) ```cmake cmake_minimum_required(VERSION 3.10) project(FileStatTool) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_executable(file_stat main.cpp) # 添加运行目标(可选扩展) add_custom_target(run COMMAND file_stat test.txt COMMAND python plot.py WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "正在运行 file_stat 并生成图表..." ) ``` --- ### 5. 测试文本示例(test.txt) ```text Hello world! This is a test file. Hello C++ programming. Welcome to C++ world. Python is great. I love coding in Python. Code once, run anywhere. Code efficiently. This is simple and effective testing. No empty lines here. Another line with hello and code. We like Python and C++ equally. More testing for C++ and Python. Final line to complete the test. ``` --- ### 6. 编译与运行说明(README.md) ```markdown # 简易文件内容统计工具 ## 功能说明 - 使用 C++ 统计文本文件的行数、单词数及高频词; - 将结果写入 `result.txt`; - 使用 Python 生成 Top5 单词柱状图 `top5.png`; - 支持 CMake 构建。 ## 编译步骤(Linux/macOS/Windows 均适用) ```bash mkdir build cd build cmake .. make ``` ## 运行方式 ### 方法一:直接运行 ```bash ./file_stat ../test.txt python ../plot.py ``` ### 方法二:使用 CMake 的 run 目标(需支持) ```bash make run ``` ## 输出文件 - `result.txt`:包含统计结果; - `top5.png`:高频词柱状图。 ## 遇到的问题及解决方法 1. **问题**:中文路径或编码导致乱码 **解决**:确保文本文件为 UTF-8 编码,避免含中文路径。 2. **问题**:Python 找不到 `matplotlib` **解决**:安装依赖 `pip install matplotlib` ``` --- ## 知识点 - **文件流操作(`std::ifstream`, `std::ofstream`)**:用于读写文本文件,支持逐行处理。 - **字符串处理(`std::tolower`, 字符遍历分割)**:统一大小写并按标点分隔单词。 - **STL 容器(`std::map`, `std::vector`)**:`map` 计数,`vector` 排序取 Top5。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值