You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python移除Java源码文件中仅含单个大括号的行

How to Remove Lines Containing Only a Single Brace { or } in Java Source Files

Let's fix your Python script to correctly filter out lines that contain only a single { or } (with any surrounding whitespace) without accidentally modifying lines that have braces alongside other code.

What's Wrong with Your Current Code?

Your existing approach has three key issues:

  1. Incorrect character check: line[0].lstrip() targets only the first character of the line, which fails to account for lines with leading whitespace (like }). Stripping a single character also doesn’t tell you anything about the rest of the line.
  2. Broken logic: Using not A or not B means almost every line gets retained—this is the opposite of what you want. You need to check if the line, after stripping whitespace, is not just { or }.
  3. Unsafe file handling: Trying to write back to the same file while reading it will corrupt your source code. Always read all content first, filter it, then write the result back.

Fixed Python Script

Here’s the corrected code that meets your requirements:

# Step 1: Read the file and filter out unwanted lines
filtered_content = []
with open("source_code.txt", "r") as input_file:
    for line in input_file:
        stripped_line = line.strip()
        # Keep lines that aren't just a single { or }
        if stripped_line not in ("{", "}"):
            filtered_content.append(line)

# Step 2: Write the filtered content back to the original file
with open("source_code.txt", "w") as output_file:
    output_file.writelines(filtered_content)

How It Works

  1. Stripping whitespace: line.strip() removes all leading/trailing spaces, tabs, and newlines from each line. This lets us accurately check if the line’s only content is a brace.
  2. Filter logic: We only keep lines where the stripped content isn’t exactly { or }. Lines like public void putAll(...) { are retained because their stripped content has additional code.
  3. Safe file handling: We first collect all valid lines in a list, then overwrite the original file with the filtered content. This prevents data loss from simultaneous read/write operations.

Testing with Your Example Input

For your provided Java code, this script will:

  • Keep all comment lines and method signature lines (including public void putAll(Map<K, V> map) throws ValidationException {)
  • Remove the lines that contain only } (like the indented closing braces for loops/conditionals and the final method closing brace)

The output will match your expected result exactly.

内容的提问来源于stack exchange,提问作者AlyssaAlex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:06:50