英文:
Notepadd++ Python Script: Delete everything between the last 3 " - " if line starts with X
问题
在查看行末尾逆向计数“ - ”(注意空格)并删除文本,但仅当行以fx TEST开头时。
之前
TESTMouse - Dog - CAT - Fish
Mouse - Dog - CAT - Fish
TESTRat - Whale - Bird - Horse - Snake
之后
TESTMouse
Mouse - Dog - CAT - Fish
TESTRat - Whale
这已经超出了我自己的能力,我在搜索中也没有找到任何可行的解决方法。
英文:
Looking at the end of the line counting the " - " backwards (notice the spaces) and delete the text but only if the line starts with fx TEST.
Before
TESTMouse - Dog - CAT - Fish
Mouse - Dog - CAT - Fish
TESTRat - Whale - Bird - Horse - Snake
After
TESTMouse
Mouse - Dog - CAT - Fish
TESTRat - Whale
This is beyond my ability to write myself and I have not found anything that would work in my searches.
答案1
得分: 0
以下是使用Python的字符串函数编写的非常简单的答案,可能可以使用正则表达式来缩短答案。请测试它并告诉我是否有任何问题。
with open("testfile.txt", "r") as f:
lines = f.readlines()
with open("testfile.txt", "w") as f:
for line in lines:
# 去除末尾的换行符
line = line.rstrip('\n')
if line.startswith("TEST"):
# 将行拆分为以 ' - ' 为分隔符的部分
parts = line.split(' - ')
# 保留前3个部分
if len(parts) > 3:
line = ' - '.join(parts[:-3])
f.write(line + '\n')
请注意,代码部分未进行翻译,只返回翻译好的内容。
英文:
Here is a very simple answer using Pythons string functions, probably could get a bit shorter of an answer with regex. Please test it and tell me if you have any issues.
with open("testfile.txt", "r") as f:
lines = f.readlines()
with open("testfile.txt", "w") as f:
for line in lines:
# strip trailing newline
line = line.rstrip('\n')
if line.startswith("TEST"):
# split line into parts from ' - '
parts = line.split(' - ')
# keep first 3 parts
if len(parts) > 3:
line = ' - '.join(parts[:-3])
f.write(line + '\n')
答案2
得分: 0
不需要使用Notepad++ PythonScript,简单的查找和替换就足够了:
- Ctrl+H
- 查找内容:
^TEST.*?\K(?: - \w+){3}$
- 替换为:
LEAVE EMPTY
- 勾选 区分大小写
- 勾选 环绕搜索
- 选择 正则表达式
- 取消勾选 匹配换行符
- 全部替换
解释:
^ # 行首
TEST # 字面上的 TEST
.*? # 0 或多个任意字符,非贪婪模式
\K # 忘记我们到这个位置为止所看到的所有内容
(?: # 非捕获组
- \w+ # 空格、连字符、空格,1 个或多个单词字符
){3} # 结束组,必须出现 3 次
$ # 行尾
替换:
屏幕截图(之前):
屏幕截图(之后):
英文:
No needs for Notepad++ PythonScript, a simple find and replace is enough:
- <kbd>Ctrl</kbd>+<kbd>H</kbd>
- Find what:
^TEST.*?\K(?: - \w+){3}$
- Replace with:
LEAVE EMPTY
- TICK Match case
- TICK Wrap around
- SELECT Regular expression
- UNTICK
. matches newline
- <kbd>Replace all</kbd>
Explanation:
^ # beginning of line
TEST # literally
.*? # 0 or more any character, not greedy
\K # forget all we have seen until this position
(?: # non capture group
- \w+ # space, hyphen, space, 1 or more word character
){3} # end group, must appear 3 times
$ # end of line
Replacement:
Screenshot (before):
Screenshot (after):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论