Python 使用正则表达式从文本文件中提取字符串

Python 使用正则表达式从文本文件中提取字符串,python,python-3.x,Python,Python 3.x,基本上我有一个txt文档,里面有这个 The sound of a horse at a gallop came fast and furiously up the hill. "So-ho!" the guard sang out, as loud as he could roar. "Yo there! Stand! I shall fire!" The pace was suddenly checked, and, with much splashing and floundering,

基本上我有一个txt文档,里面有这个

The sound of a horse at a gallop came fast and furiously up the hill.
"So-ho!" the guard sang out, as loud as he could roar.
"Yo there! Stand! I shall fire!"
The pace was suddenly checked, and, with much splashing and floundering, a man's voice called from the mist, "Is that the Dover mail?"
"Never you mind what it is!" the guard retorted. "What are you?"
"_Is_ that the Dover mail?"
"Why do you want to know?"
"I want a passenger, if it is."
"What passenger?"
"Mr. Jarvis Lorry."
Our booked passenger showed in a moment that it was his name.
The guard, the coachman, and the two other passengers eyed him distrustfully.
使用正则表达式我需要在双引号内打印所有内容,我不需要完整的代码,我只需要知道应该如何操作,哪个正则表达式最有用。请给我提示和指点

r'(“*?”)
将匹配双引号内的每个字符串。括号表示捕获的组,
匹配每个字符(换行除外),
*
表示重复,
使其不贪婪(在下一个双引号之前停止匹配)。如果需要,请包括
re.DOTALL
选项,以使
也与换行符匹配。

这应该可以做到(如下说明):

结果:

So-ho!
Yo there! Stand! I shall fire!
Is that the Dover mail?
Never you mind what it is!
What are you?
_Is_ that the Dover mail?
Why do you want to know?
I want a passenger, if it is.
What passenger?
Mr. Jarvis Lorry.
r'(*?”
将匹配双引号内的每个字符串。括号表示一个捕获组,因此只能获取不带双引号的文本。
匹配每个字符(换行符除外),而
*
表示“最后一件事的零或多个”,最后一件事就是
*
后面的
使
*
成为“非贪婪的”,这意味着它尽可能少地匹配。如果你没有使用
,你只会得到一个结果;包含第一个双引号和最后一个双引号之间的所有内容的字符串

如果要提取跨行字符串,可以包括re.DOTALL标志,以便
也将匹配换行符。如果您想这样做,请使用
re.findall(r''(.*)”,txt,re.DOTALL)
。换行符将包含在字符串中,因此您必须对此进行检查


解释不可避免地与@TigerhawkT3的答案相似/基于@TigerhawkT3的答案。也投票支持这个答案

我会用这个漂亮的答案。所以我不应该发布一个符合你要求的答案?具体来说,
*
表示前一个模式的任何数字(零或更多)——在本例中为
,即任何字符。我遇到了一个问题,即在具有多个“”的行上,它会将其打印在与前一个相同的行上,而我需要将其放在新行上,在它找到第二个“it does a newline”之后,是否还有其他方法可以这样做?@NickAdams-而不是
print(''.join(strings))
,而是
print(*strings,sep='\n')
。如果您发现您的答案与之前的答案完全相同,通常最好删除重复答案,而不是将旧答案复制到您自己的答案中。这有助于减少“噪音”“供游客使用。@TigerhawkT3,明白,但它不仅仅是复制品。我已经有了代码和输出,并想添加一个解释,但我不想混淆它,使它与您的非常不同:)。我是否应该在没有解释的情况下留下我的答案,并期望观众阅读这两个答案,这样就不会有任何重叠?显然,对同一个问题的回答往往会有些重叠。我确实比你解释得多了一点点;但同样,任何好的解释都是相似的。我确实提到了你的答案:)。你是从字符串而不是像我一样的文本文件中读取的。当我这样做,但从一个文本文件,如果一行有多个引号,它会打印在同一行。第二个“@NickAdams,当你从文本文件中读取时,文本变成字符串,所以它应该是一样的。你能显示你正在使用的代码吗?用open('atotc.txt')作为f:for行导入re,在f:strings=re.findall(r')(.*)行)打印(''.join(strings))
So-ho!
Yo there! Stand! I shall fire!
Is that the Dover mail?
Never you mind what it is!
What are you?
_Is_ that the Dover mail?
Why do you want to know?
I want a passenger, if it is.
What passenger?
Mr. Jarvis Lorry.