[英]Extract values from text and convert to JSON using python
我在文件中有一個文本,如下所示。 我需要從文本中提取值作為 json 格式。
輸入.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
- - - - - - - - -
使用 python 我需要將輸出作為輸出
{"NAME" :"Game" }
{"SQL" :"case @ when students1.db end" }
根據您在問題中提供的數據,這樣做的方法是:
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)
這將產生以下結果:
{'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.