【问题标题】:How to extract contents between two strings in Python?如何在 Python 中提取两个字符串之间的内容?
【发布时间】:2020-05-22 04:55:42
【问题描述】:

我对 Python 还很陌生。

我有一个包含将近 500k 行文本的 .txt 文件。大体结构是这样的:

WARC-TREC-ID:

你好

我的

名字

WARC-TREC-ID:

例子

文字

WARC-TREC-ID:

我想提取“WARC-TREC-ID:”关键字之间的所有内容。

这是我已经尝试过的:

    content_list = []

with open('C://Users//HOME//Desktop//Document_S//corpus_test//00.txt', errors = 'ignore') as openfile2:
    for line in openfile2:
        for item in line.split("WARC-TREC-ID:"):
            if "WARC-TREC-ID:" in item:
                content = (item [ item.find("WARC-TREC-ID:")+len("WARC-TREC-ID:") : ])
                content_list.append(content)

这会返回一个空列表。

我也试过了:

    import re

with open('C://Users//HOME//Desktop//Document_S//corpus_test//00.txt', 'r') as openfile3:
    
    m = re.search('WARC-TREC-ID:(.+?)WARC-TREC-ID:', openfile3)
    if m: 
        found = m.group(1)

这会导致 TypeError: expected string or bytes-like object

【问题讨论】:

    标签: python


    【解决方案1】:

    试试:

    content_list = []
    with open(filename) as infile:
        for line in infile:               #Iterate each line
            if 'WARC-TREC-ID:' in line:   #check if line contains 'WARC-TREC-ID:'
                content_list.append([])   #Append empty list
            else:
                content_list[-1].append(line)   #Append content
    
    print(content_list)
    

    【讨论】:

    • 以下行出现列表索引超出范围错误:“content_list[-1].append(line)”
    • 尝试声明content_list = [[]]
    • 我更改了 content_list 的声明,并删除了第一个 'WARC-TREC-ID:' 之前的所有文本:现在,我收到以下错误“UnicodeDecodeError: 'charmap' codec can't decode位置 5720 中的字节 0x8f:字符映射到 "
    • 我在打开的文件行中添加了一个 errors = 'ignore' 参数,它起作用了。谢谢
    【解决方案2】:

    在您的第二种方法中,您应该将文件内容作为string 传递为it expects a string argument, not file。这也只会返回该字符串的第一次出现。您可能想使用findall

    【讨论】:

      【解决方案3】:

      对于包含您的数据的文件:

      raw_data = open('data.txt', 'r').read()
      result = [x for x in raw_data.split() if x != 'WARC-TREC-ID:']
      

      输出:

      ['hello', 'my', 'name', 'is', 'example', 'text']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-21
        • 2019-10-26
        • 1970-01-01
        • 2010-11-29
        • 2021-01-17
        相关资源
        最近更新 更多