如何解析txt文件中的信息? Python的3.0
问题描述:
这仅仅是一个代码示例如何解析txt文件中的信息? Python的3.0
{
"created_at": "Fri Jan 31 05:51:59 +0000 2014",
"favorited": false,
"lang": "en",
"place": {
"country_code": "US",
"url": "https://api.twitter.com/1.1/geo/id/cf44347a08102884.json"
},
"retweeted": false,
"source": "<a href=\"http://tapbots.com/software/tweetbot/mac\" rel=\"nofollow\">Tweetbot for Mac</a>",
"text": "Active crime scene on I-59/20 near Jeff/Tusc Co line. One dead, one injured; shooting involved. Police search in the area; traffic stopped",
"truncated": false
}
如何解析这个在python
这样我就可以得到text
或lang
的信息?
答
我假设这个片段是不完整的,因为它看起来像json
,但目前无效。假设一个有效json
文件,那么你可以使用json
模块:
>>> import json
>>> s = """{"lang": "en", "favorited": false, "truncated": false, ... }"""
>>> data = json.loads(s)
>>> data['lang']
'en'
>>> data['text']
'Active crime scene on I-59/20 near Jeff/Tusc Co line. One dead, one injured; shooting involved. Police search in the area; traffic stopped'
txt文件和蟒蛇编码是相互独立的2个不同的文件。我试图调用(在Python中)这个文本文件(称为CrimeReport.txt),然后解析它。我将如何做到这一点。 – kel