【问题标题】:python find and replace new linespython查找和替换新行
【发布时间】:2014-03-16 10:00:08
【问题描述】:

我有以下文字:

Name:John
Age:23
Status:Single
Gender:Male
Name:Merry
Age:19
Gender:Female
Name:Alex
Age:20
Status:Single
Gender:Male

我用下面的notepad++查找和替换

Find:\r\nAge:
Replace:!Age;
Find:\r\nStatus:
Replace:!Status;
Find:\r\nGender:
Replace:!Gender;

有输出:

Name:John!Age;23!Status;Single!Gender;Male
Name:Merry!Age;19!Gender;Female
Name:Alex!Age;20!Status;Single!Gender;Male

如何使用notepad++ python脚本而不是查找和替换来做到这一点

我可以使用下面的语句来连接一些编辑的行吗??

editor.pyreplace(r"\r$\n", "!", 0, Editor.INCLUDELINEENDINGS)

【问题讨论】:

    标签: python replace notepad++ newline


    【解决方案1】:

    做一个正则表达式替换,搜索会不会更容易

    \r\n(?!Name)
    

    并用!替换所有匹配项?

    【讨论】:

      【解决方案2】:

      在 Python 中:

      with open('outfile.txt', 'w') as outhandle, open('file.txt', 'r') as inhandle:
              outhandle.write(inhandle.read().replace('\nAge:','!Age;').replace('\nStatus:','!Status;').replace('\nGender:','!Gender;'))
      

      输出将被写入 outfile.txt 并将输入文件视为“file.txt”。

      【讨论】:

      • 我不想指定文件名。是否可以直接在文件上运行脚本
      【解决方案3】:

      我认为您最简单的选择是用感叹号替换所有前面没有 Name 的回车/换行符:

      import re
      with open('input.txt', 'r') as f:
          print re.sub('\r?\n(?!Name)', '!', f.read())
      

      输出:

      Name:John!Age:23!Status:Single!Gender:Male
      Name:Merry!Age:19!Gender:Female
      Name:Alex!Age:20!Status:Single!Gender:Male
      

      【讨论】:

      • 语法错误:语法无效
      猜你喜欢
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2013-02-09
      相关资源
      最近更新 更多