[英]Extract values from text and convert to JSON using python
I have a text in a file as shown below.我在文件中有一个文本,如下所示。 I need to extract values from text as json format.
我需要从文本中提取值作为 json 格式。
Input.txt输入.txt
- - - - - —---
Name: Game
Students: 10
Sql : case @
when students.db end
LIST: write
Total:Game1
- - - - - —---
Name: Game1
Students: 10
Sql : case @
when students1.db end
LIST: write
Attribute: PL Game1
- - - - - - - - - - -
Name: Game11
Students: 10
Sql : case @
when students11.db end
LIST: write
- - - - - - - - -
Using python i need to get output as Output使用 python 我需要将输出作为输出
{"NAME" :"Game" }
{"SQL" :"case @ when students1.db end" }
Based on the data you provided in your question, on way to do it is this:根据您在问题中提供的数据,这样做的方法是:
with open("data.txt", "r") as inFile:
finalOutput = []
content = inFile.read().replace('-','').replace('—','').replace('@\n', '@').strip().split('\n\n')
content = [" ".join(item.split()) for elem in content for item in elem.split('\n')]
content = [elem for elem in content if elem != '']
finalOutput = [{elem.split(":")[0].strip() : elem.split(":")[1].strip()} for elem in content]
for elem in finalOutput:
print(elem)
This will yield the following result:这将产生以下结果:
{'Name': 'Game'}
{'Students': '10'}
{'Sql': 'case @ when students.db end'}
{'LIST': 'write'}
{'Total': 'Game1'}
{'Name': 'Game1'}
{'Students': '10'}
{'Sql': 'case @ when students1.db end'}
{'LIST': 'write'}
{'Attribute': 'PL Game1'}
{'Name': 'Game11'}
{'Students': '10'}
{'Sql': 'case @ when students11.db end'}
{'LIST': 'write'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.