如何从 txt 文件中提取某些内容?

How can I extract certain content from a txt file?

这是我的代码:

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}}}]}

但是,我只需要没有文本的日期时间值。 我怎样才能做到这一点?

您有 JSON 回复。您可以使用 JSON 模块。

例如:

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'])