Python 如何从txt文件中提取特定内容?

Python 如何从txt文件中提取特定内容?,python,web-scraping,raspberry-pi,urllib,Python,Web Scraping,Raspberry Pi,Urllib,这是我的代码: import urllib.request import urllib.parse x = urllib.request.urlopen('http://transport.opendata.ch/v1/connections? from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure') data = x.read()`enter code here` save

这是我的代码:

import urllib.request 
import urllib.parse
x = urllib.request.urlopen('http://transport.opendata.ch/v1/connections? 
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure')
data = x.read()`enter code here`

saveFile = open('Ergebnis4.txt', 'w')
saveFile.write(str(data))
saveFile.close()here
当我运行它时,我得到以下信息:

{"connections":[{"from":{"prognosis":{"departure":"2018-06- 
07T11:52:00+0200"}}},{"from":{"prognosis":{"departure":"2018-06- 
07T12:22:00+0200"}}},{"from":{"prognosis":{"departure":"2018-06- 
07T12:53:00+0200"}}},{"from":{"prognosis":{"departure":null}}}]}
但是,我只需要Datetime值,不需要文本。
我怎样才能做到这一点呢?

您有一个JSON响应。您可以使用JSON模块

Ex:

import json
with open('Ergebnis4.txt', 'w') as outfile:
    for i in json.loads(data)["connections"]:
        saveFile.write(i['from']['prognosis']['departure'])

您可以使用正则表达式从响应中提取日期时间

# ...
data = x.read()

dates = re.findall('\d{4}[^+]*\+\d{4}', str(data))
dates = '\n'.join(dates)

saveFile = open('Ergebnis4.txt', 'w')
saveFile.write(dates)
saveFile.close()

这就是你可以得到的方法:

import requests

res = requests.get("http://transport.opendata.ch/v1/connections?from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
for item in res.json()['connections']:
    print(item['from']['prognosis']['departure'])
输出:

2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
None
或使用urllib模块:

from urllib.request import urlopen
import json

res = urlopen("http://transport.opendata.ch/v1/connections?from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
for item in json.load(res)['connections']:
    print(item['from']['prognosis']['departure'])

这个响应就是JSON,您应该研究如何解析JSON响应。这个解决方案确实很有帮助,但是您知道有没有一种方法可以不用导入请求就可以做到这一点吗?