python - 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 初学者,我在谷歌上搜索这个主题。任何指针将不胜感激。
解决方案
如果你想坚持你的 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 循环。就我自己而言,我会坚持使用上面的状态机方法,并使其足够强大以处理所有合理预期的边缘情况。
推荐阅读
- r - Rstudio 中的 ROracle 性能问题
- java - Spring 安全性阻止输出请求。连接超时
- pandas - pandas 读取多索引数据帧(反向 to_string() )
- bash - ftp提示用户名和密码时BASH自动应答
- shell - 即使后面跟着零,如何从字符串中提取有效数字
- c++ - 类私有成员 C++ 的动态内存分配与 std::vector
- elasticsearch - 在 kubernetes 中启动 elasticsearch 的地方创建了新节点
- java - 使用java将给定的时间转换为纳秒精度
- php - 在 Woocommerce 订阅中显示每月变化价格
- c++ - 如果在子目录中定义了测试,CMake 不会运行测试