python - python将下一个字符串刮到给定的字符串
问题描述
我有 +1000 个 txt 文件要抓取(Python)。我已经创建了file_list
列出所有 .txt 文件路径的变量。我有五个字段要抓取:file_form、日期、公司、公司 ID 和价格范围。对于前四个变量,我没有问题,因为它们在每个 .txt 文件开头的单独行中非常结构化:
FILE FORM: 10-K
DATE: 20050630
COMPANY: APPLE INC
COMPANY CIK: 123456789
我对这四个使用了以下代码:
import sys, os, re
exemptions=[]
for eachfile in file_list:
line2 = "" # for the following loop I need the .txt in lines. Right now, the file is read one in all. Create var with lines
with open(eachfile, 'r') as f:
for line in f:
line2 = line2 + line # append each line. Shortcut: "line2 += line"
if "FILE FORM" in line:
exemptions.append(line.strip('\n').replace("FILE FORM:", "")) #append line stripping 'S-1\n' from field in + replace FILE FORM with blanks
elif "COMPANY" in line:
exemptions.append(line.rstrip('\n').replace("COMPANY:", "")) # rstrip=strips trailing characters '\n'
elif "DATE" in line:
exemptions.append(line.rstrip('\n').replace("DATE:", "")) # add field
elif "COMPANY CIK" in line:
exemptions.append(line.rstrip('\n').replace("COMPANY CIK:", "")) # add field
print(exemptions)
这些给了我一个exemptions
包含所有相关值的列表,如上例所示。但是,“价格范围”字段位于 .txt 文件的中间,如下所示:
We anticipate that the initial public offering price will be between $ and
$ per share.
而且我不知道如何将其保留$whateveritis;and $whateveritis;per share.
为我的最后一个第五个变量。好消息是很多文件使用相同的结构,有时我有 $amounts 而不是“ ”。示例:We anticipate that the initial public offering price will be between $12.00 and $15.00 per share.
。
我希望这个“12.00;and;15.00”作为exemptions
列表中的第五个变量(或者类似的东西,我可以在 csv 文件中轻松地工作)。
非常感谢你。
解决方案
看起来您已经导入了正则表达式,那么为什么不使用它呢?像这样的正则表达式\$[\d.]+\ and \$[\d.]+
应该与价格匹配,然后您可以从那里轻松地对其进行细化:
import sys, os, re
exemptions=[]
for eachfile in file_list:
line2 = ""
with open(eachfile, 'r') as f:
for line in f:
line2 = line2 + line
m = re.search('\$[\d.]+\ and \$[\d.]+', line)
if "FILE FORM" in line:
.
.
.
elif m:
exemptions.append(m.group(0)) # m.group(0) will be the first occurrence and you can refine it from there
print(exemptions)
推荐阅读
- sql - 数据库的请求限制为 30 并且已达到:该错误的请求计数的哪些状态?
- javascript - 如何在jquery中使用鼠标位置移动溢出的元素
- javascript - 具有不可拖动子图像的可拖动 div 上的 FireFox 问题
- css - Gantry 5 网格系统与 Bootstrap 4 相同
- postgresql - 什么是postgresql查询来查找没有时区的时间戳
- ruby-on-rails - “有没有办法在 ActiveModel::Type::Value 中引发错误?”
- android - 使用 Kotlin 从 RecyclerAdapter 更改 MainActvity 中的 TextView
- php - 如何在PHP中显示2个日期之间的所有天数
- php - PHP下载的文件在firefox拼图中是0字节
- angular - 如何在构建期间添加模块 - Angular