python - 从网络抓取中搜索文本并将接下来的 4 行转换为 python 数据框
问题描述
我已经能够从网站上刮掉一些文本,但在尝试将文本转换为某种数据框时遇到了麻烦(最好然后与熊猫一起使用)
print(text)
webscrape 的输出给了我所有的文本:
Example text paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Section 1 - "Summary"
1 - sdgge
2 - hjsdhdc
3 - sahdfda
4 - sahfdfds
Example text paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Section 2 - "Introduction"
1 - abcdef
2 - jhfdgsa
3 - sadgffe
4 - sdjddasd
我的下一步是尝试将数据转换为具有以下内容的表:
Section 1 | Summary | 1 - sdgge | 2 - hjsdhdc | 3 - sahdfda| 4 - sahfdfds|
Section 2 | Introduction | 1 - abcdef| 2 - jhfdgsa | 3 - sadgffe| 4 - sdjddasd|
文本文本中的部分最多为 10-15
这些部分随机分布在其他段落中,因此是否可以搜索“第 1 部分”,然后返回下面的 4 行等等?
非常感谢!
解决方案
已编辑
我会通过使用正则表达式逻辑遍历每一行来解决这个问题:
my_lines = my_text.split("\n")
# instantiate an empty list of records
records = []
my_patterns = {
"section":re.compile("section\s*[0-9]+", re.I),
"1":re.compile('1 - ([a-z]+)'),
"2":re.compile('2 - ([a-z]+)'),
"3":re.compile('3 - ([a-z]+)'),
"4":re.compile('4 - ([a-z]+)')
}
rec = {}
# Loop through each line, perform logic
for x in my_lines:
for key, pattern in my_patterns.items():
if pattern.search(x):
# get the value
my_value = pattern.findall(x)[0]
if key == "section":
# save the records
if len(rec)>0:
records.append(rec)
# start a new record
rec = {}
# always add to the record
rec[key] = my_value
# # when done looping, add the last record
records.append(rec)
# # convert to a dataframe
df = pd.DataFrame(records)
section 1 2 3 4
0 Section 1 sdgge hjsdhdc sahdfda sahfdfds
1 Section 2 abcdef jhfdgsa sadgffe sdjddasd
推荐阅读
- ios - 如何创建一个在后台正常运行的iOS闹钟
- javascript - 基于javascript模块中的数据类型构建不同的模板
- apl - 在 APL 中是否有将字符串连接成一个字符标量的符号?
- php - SQL 选择:多个值
- c# - 如何在 C# 中更改语音合成器的语音或速度
- exception - perl 5 鲤鱼的 raku 类似物是什么?
- java - 使用自定义收集器对象对 Java Stream 中的哈希映射中的值进行分组?
- javascript - 即使firebase工具说我登录,为什么角度火说我没有登录?
- javascript - 如何在 Nextjs 9 中设置请求标头
- javascript - 在嵌套数组对象中为 SectionList 数据按索引设置状态