【发布时间】:2019-09-29 09:46:32
【问题描述】:
我是 python 新手,我正在使用正则表达式处理一个文本文件以提取 id 并附加一个列表。我在下面写了一些python,打算构造一个看起来像这样的列表
["10073710","10074302","10079203","10082213"...and so on]
相反,我看到了一个包含一堆详细标签的列表结构。我假设这是正常行为,并且 finditer 函数在找到匹配项时会附加这些标签。但是响应有点混乱,我不确定如何关闭/删除这些添加的标签。请参阅下面的屏幕截图。
谁能帮我修改下面的代码,以便我可以实现列表的预期结构?
import re
#create a list of strings
company_id = []
#open file contents into a variable
company_data = open(r'C:\Users\etherealessence\Desktop\company_data_test.json', 'r', encoding="utf-8")
#read the line structure into a variable
line_list = company_data.readlines()
#stringify the contents so regex operations can be performed
line_list = str(line_list)
#close the file
company_data.close()
#assign the regex pattern to a variable
pattern = re.compile(r'"id":([^,]+)')
#find all instances of the pattern and append the list
#https://stackoverflow.com/questions/12870178/looping-through-python-regex-matches
for id in re.finditer(pattern, line_list):
#print(id)
company_id.append(id)
#test view the list of company id strings
#print(line_list)
print(company_id)
【问题讨论】:
-
Regex 在这里是一个糟糕的解决方案。你可能想要像 JSON Path 这样的东西来直接查询结构。
标签: python regex regex-lookarounds regex-group regex-greedy