首页 > 解决方案 > Python Readline 循环和子循环

问题描述

我正在尝试遍历 python 中的一些非结构化文本数据。最终目标是将其构建在数据框中。现在我只是想在一个数组中获取相关数据并理解 python 中的 readline() 功能。

这是文本的样子:

Title: title of an article
Full text: unfortunately the full text of each article,
is on numerous lines. Each article has a differing number 
of lines. In this example, there are three..
Subject: Python
Title: title of another article
Full text: again unfortunately the full text of each article,
is on numerous lines.
Subject: Python

对于同一个文件中的许多文本文章,重复这种相同的格式。到目前为止,我已经弄清楚如何提取包含某些文本的行。例如,我可以遍历它并将所有文章标题放在一个列表中,如下所示:

a = "Title:"
titleList = []
sample = 'sample.txt'
with open(sample,encoding="utf8") as unstr:  
for line in unstr:
      if a in line:
        titleList.append(line)

现在我想做以下事情:

a = "Title:"
b = "Full text:"
d = "Subject:"
list = []
sample = 'sample.txt'
with open(sample,encoding="utf8") as unstr:  
for line in unstr:
  if a in line:
    list.append(line)
  if b in line:
     1. Concatenate this line with each line after it, until i reach the line that includes "Subject:". Ignore the "Subject:" line, stop the "Full text:" subloop, add the concatenated full text to the list array.<br>
     2. Continue the for loop within which all of this sits

作为一名 Python 初学者,我在谷歌上搜索这个主题。任何指针将不胜感激。

标签: pythonpandasdataframenlpreadline

解决方案


如果你想坚持你的 for 循环,你可能需要这样的东西:

titles = []
texts = []
subjects = []

with open('sample.txt', encoding="utf8") as f:
    inside_fulltext = False
    for line in f:
        if line.startswith("Title:"):
            inside_fulltext = False
            titles.append(line)
        elif line.startswith("Full text:"):
            inside_fulltext = True
            full_text = line
        elif line.startswith("Subject:"):
            inside_fulltext = False
            texts.append(full_text)
            subjects.append(line)
        elif inside_fulltext:
            full_text += line
        else:
            # Possibly throw a format error here?
            pass

(有几件事:Python 的名字很奇怪,当你写 时list = [],你实际上是在覆盖list类的标签,这可能会在以后给你带来问题。你真的应该把list,set等当作关键字对待——甚至认为 Python从技术上讲不会 - 只是为了省去你的麻烦。此外,startswith鉴于您对数据的描述,该方法在这里更精确。)

或者,您可以将文件对象包装在迭代器(i = iter(f),然后next(i))中,但这会导致捕获StopIteration异常时有些头疼 - 但它会让您对整个事情使用更经典的 while 循环。就我自己而言,我会坚持使用上面的状态机方法,并使其足够强大以处理所有合理预期的边缘情况。


推荐阅读