在.txt文件中搜索特定单词,并在该单词之后打印数据

时间:2019-01-28 17:30:31

标签: python

我是python的新手,所以请听我说。我一直到处寻找,找不到如何专门做我需要的事情。我从网站请求天气信息,然后将其转换为.txt文件。我想在搜索的单词旁边打印该值。请参见下面的.txt文件摘录:

{"cod": "200", "message": 0.004, "cnt": 10, "list": [{"dt": 1548698400, "main": {"temp": 275.32, "temp_min": 274.915, "temp_max": 275.32,

我想搜索temp,并打印275.32

添加了我的代码| API密钥已删除|与“ test”相关的单词围绕变量运行,以查看输出是否发生变化

import requests
import re
import time
import json
from datetime import datetime, timedelta
curDate=datetime.now().timestamp()
print(datetime.utcfromtimestamp(curDate).strftime('%Y-%m-%d %H:%M:%S'))
system = True

while system:
    userInput=input("Type exit to leave or enter your city of choice: ")
    findExit = re.search(r'xit', userInput)
    findTheExit = re.search(r'XIT', userInput)

    if str(findExit)=='None' and str(findTheExit)=='None':
        weatherInfo = requests.get('https://api.openweathermap.org/data/2.5/forecast?q='+userInput+',us&appid=api_key_here&cnt=10')
        test = weatherInfo.json()
        testTwo = json.dumps(test)
        info=json.loads(testTwo)
        with open("Data.txt", "a") as outfile:
            json.dump(test, outfile)
# Yassine Addi code added
        with open('Data.txt', 'r') as fp:
            data = json.load(fp)
            for item in data['list']:
                print(item['main']['temp'])
 # Yassine Addi end
    else:
        print("System turning off, goodbye")
        system=False

1 个答案:

答案 0 :(得分:1)

如果您的文件是有效的JSON,请执行此操作

import json

with open('a.txt', 'r') as fp:
    data = json.load(fp)
    for item in data['list']:
        print(item['main']['temp']) # prints 275.32

考虑到a.txt包含

{
    "cod": "200",
    "message": 0.004,
    "cnt": 10,
    "list": [
        {
            "dt": 1548698400,
            "main": {
                "temp": 275.32,
                "temp_min": 274.915,
                "temp_max": 275.32
            }
        }
    ]
}
相关问题