首页 > 解决方案 > 如何在文本文件中提取引用的语句——Python

问题描述

我想在文本文件中查找所有引用的语句。我写了一个代码,它可以找到第一个引用的语句。但是,当我使用while 循环时,它可以遍历整个文本并找到它们,但它不起作用。这是代码:

        quoteStart = fullText.index("\"")
        quoteEnd = fullText.index("\"", quoteStart + 1)
        quotedText = fullText[quoteStart:quoteEnd+1]
        print ("{}:{}".format(quoteStart, quoteEnd))
        print (quotedText)

输出 :

250:338

"When we talk about the Hiroshima and Nagasaki bombing, we never talk about Shinkolobwe,"

我怎样才能添加while循环来遍历整个文本?

标签: pythontextwhile-loopquotes

解决方案


提供一个最小的工作示例总是好的,即如果您提供了fullText.

您不需要while循环来执行此操作。正则表达式将是一个更简单的解决方案。

让我们假设, fullText = '"When we talk about the Hiroshima and Nagasaki bombing, we never talk about Shinkolobwe," was what one said and "I agree." was what another said.'

您可以使用如下所示的正则表达式。

import re

quotedText = re.findall(r'"([^"]*)"', fullText)

print(quotedText)

结果:

['When we talk about the Hiroshima and Nagasaki bombing, we never talk about Shinkolobwe,', 'I agree.']

r'"([^"]*)"'是一个原始字符串,它表示一个正则表达式,以匹配任何出现次数的任何内容,但两个双引号之间的双引号除外。

一个很好的解释是here


推荐阅读