格式化字符串,去除多余空格,按关键词换行 Args: input_string: 输入的原始字符串 line_break_keyword: 用于换行的关键词 remove_empty_lines: 是否移除空行 trim_whitespace: 是否修剪首尾空白 Returns: 格式化后的字符串
(self, input_string, line_break_keyword, remove_empty_lines=True, trim_whitespace=True)
| 27 | CATEGORY = "PDuse/Text" |
| 28 | |
| 29 | def format_string(self, input_string, line_break_keyword, remove_empty_lines=True, trim_whitespace=True): |
| 30 | """ |
| 31 | 格式化字符串,去除多余空格,按关键词换行 |
| 32 | |
| 33 | Args: |
| 34 | input_string: 输入的原始字符串 |
| 35 | line_break_keyword: 用于换行的关键词 |
| 36 | remove_empty_lines: 是否移除空行 |
| 37 | trim_whitespace: 是否修剪首尾空白 |
| 38 | |
| 39 | Returns: |
| 40 | 格式化后的字符串 |
| 41 | """ |
| 42 | if not input_string: |
| 43 | return ("",) |
| 44 | |
| 45 | try: |
| 46 | # 首先去除所有多余的空白字符,但保留单个空格 |
| 47 | # 将多个连续空白字符(包括空格、制表符、换行符)替换为单个空格 |
| 48 | cleaned_string = re.sub(r'\s+', ' ', input_string) |
| 49 | |
| 50 | # 去除首尾空白 |
| 51 | if trim_whitespace: |
| 52 | cleaned_string = cleaned_string.strip() |
| 53 | |
| 54 | # 如果没有关键词,直接返回清理后的字符串 |
| 55 | if not line_break_keyword: |
| 56 | return (cleaned_string,) |
| 57 | |
| 58 | # 在关键词后添加换行符 |
| 59 | # 使用正则表达式查找关键词,并在其后添加换行符 |
| 60 | pattern = f'({re.escape(line_break_keyword)})' |
| 61 | formatted_string = re.sub(pattern, r'\1\n', cleaned_string) |
| 62 | |
| 63 | # 处理结果行 |
| 64 | lines = formatted_string.split('\n') |
| 65 | processed_lines = [] |
| 66 | |
| 67 | for line in lines: |
| 68 | # 去除每行的首尾空白 |
| 69 | if trim_whitespace: |
| 70 | line = line.strip() |
| 71 | |
| 72 | # 根据选项决定是否保留空行 |
| 73 | if remove_empty_lines: |
| 74 | if line: # 只添加非空行 |
| 75 | processed_lines.append(line) |
| 76 | else: |
| 77 | processed_lines.append(line) |
| 78 | |
| 79 | # 重新组合字符串 |
| 80 | result = '\n'.join(processed_lines) |
| 81 | |
| 82 | return (result,) |
| 83 | |
| 84 | except Exception as e: |
| 85 | print(f"StringFormatter错误: {e}") |
| 86 | return (input_string,) # 发生错误时返回原始字符串 |
nothing calls this directly
no outgoing calls
no test coverage detected