从文本文件中删除由“++$+++”分隔的字符串的正则表达式代码?

2024-09-25 02:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,我想从中删除由+++$+++分隔的所有字符

文件如下:

L666256 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ Colonel Durnford... William Vereker. I hear you 've been seeking Officers?

L666257 +++$+++ u9030 +++$+++ m616 +++$+++ DURNFORD +++$+++ Good ones, yes, Mr Vereker. Gentlemen who can ride and shoot

L666369 +++$+++ u9030 +++$+++ m616 +++$+++ DURNFORD +++$+++ Your orders, Mr Vereker?
L666370 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ I'm to take the Sikali with the main column to the river

L666371 +++$+++ u9030 +++$+++ m616 +++$+++ DURNFORD +++$+++ Lord Chelmsford 
seems to want me to stay back with my Basutos.

L666372 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ I think Chelmsford wants a good man on the border Why he fears a flanking attack and requires a steady Commander in reserve.

例如,我希望第一行输出为Colonel Durnford... William Vereker. I hear you 've been seeking Officers?

而不是当前字符串L666256 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ Colonel Durnford... William Vereker. I hear you 've been seeking Officers?

我该怎么做?你知道吗


Tags: thetoyouvewilliambeenhearofficers
2条回答

读取文本文件并使用字符串方法替换精确的字符。你知道吗

示例:

txt = """L666256 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ Colonel Durnford... William Vereker. I hear you 've been seeking Officers?"""

print(' '.join(txt.split(" +++$+++ ")))

或者直接用replace()

print(txt.replace(" +++$+++ ", " "))

或者使用正则表达式和re模块。你知道吗

string = "L666256 +++$+++ u9034 +++$+++ m616 +++$+++ VEREKER +++$+++ Colonel Durnford... William Vereker. I hear you 've been seeking Officers?"
regex = r"^.*\+{3}\$\+{3}\s*"
re.sub(regex, "", string)

相关问题 更多 >