简体   繁体   English

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

[英]How can I extract certain content from a txt file?

This is my code: 这是我的代码:

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

When I run it, I get this: 运行它时,我得到以下信息:

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

However, I only need the Datetime values without the text. 但是,我只需要没有文本的Datetime值。 How could I achieve that? 我该如何实现?

You can extract datetimes from the response with regex. 您可以使用正则表达式从响应中提取日期时间。

# ...
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()

You are having a JSON response. 您正在接收JSON响应。 You can use the JSON module. 您可以使用JSON模块。

Ex: 例如:

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

This is how you can get that: 这是您如何获得的:

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

Output: 输出:

2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
None

Or using urllib module: 或使用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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM