【问题标题】:Extract text enclosed in quotes when reading a file [duplicate]读取文件时提取引号中的文本[重复]
【发布时间】:2015-01-24 16:22:14
【问题描述】:

我正在逐行读取文件并想要获取我想要的东西。我在该行中寻找一个关键字,然后现在一个字一个字地阅读它。在 C/C++ 中,我只需将字符串放入 for 循环并遍历它说

这是我到目前为止的代码。

i = 0

with open("test.txt") as f:
    for line in f:
        if "test" in line:
            for character in line:
                if character == "\"":
                   //append all characters to a string until the 2nd quote is seen

有什么想法吗?

【问题讨论】:

  • 一个具有预期输出的例子会更好..
  • 成功了吗?如果不是,出了什么问题?
  • for character in line: 正在使用 Python 并按照您的要求迭代每个字符。那么什么你的问题到底是什么?
  • 我想抓取用引号括起来的文本
  • @jtor 你只是在重复你已经说过的话,它不会让它变得不那么模棱两可。

标签: python


【解决方案1】:

试试这个:

in_string = False
current_string = ""
strings = []

with open("test.txt") as f:
    for line in f:
        if "test" in line:
            for character in line:
                if character == '"':
                    if in_string:
                        strings.append(current_string)
                    in_string = not in_string
                    current_string = ""
                    continue
                elif in_string:
                    current_string += character

它遍历行中的所有字符,然后如果是"',它开始将前面的字符收集到一个字符串中,或​​者它停止并将收集到的字符串附加到一个列表中。

或者,使用正则表达式:

import re
strings = []

with open("test.txt") as f:
    for line in f:
        if "test" in line:
            strings.extend(re.findall(r'"(.*?)"', line, re.DOTALL))

【讨论】:

  • 谢谢,这应该足以让我开始了。
  • 您可以在没有 RE 的情况下以更简单的方式执行此操作。不幸的是,在我发布答案之前,该线程已关闭。解决方案:splitted = open('test.txt').read().split('\"')quotted = [ splitted[i] for i in range(1, len(quote_split), 2) ]
  • @Pithikos 如果没有引号,这将不起作用,并且即使它没有关闭,也会包含上次打开的引号中的内容。此外,jtor 在检查引用的单词之前检查 test 是否在行中,这是您的方法无法做到的。
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2018-05-14
  • 2018-07-09
  • 2018-01-11
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多