我有以下文字:
Name:John
Age:23
Status:Single
Gender:Male
Name:Merry
Age:19
Gender:Female
Name:Alex
Age:20
Status:Single
Gender:Male
我使用下面的记事本++查找和替换
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)
答案 0 :(得分:0)
单个正则表达式替换,搜索
会不会更容易\r\n(?!Name)
并将所有匹配替换为!
?
答案 1 :(得分:0)
我认为您最简单的选择是用感叹号替换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
答案 2 :(得分:0)
在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'。