在.txt中查找变量并比较两个变量中的值?

时间:2015-12-22 09:17:59

标签: python regex

let url = NSURL.fileURLWithPath(path)
        moviePlayer = MPMoviePlayerController(contentURL: url)
 if let player = moviePlayer {
player.view.frame = videoBackgroundView.bounds
            player.prepareToPlay()
            player.scalingMode = .Fill
            videoBackgroundView.addSubview(player.view)

        }

CODE:

----bDdefsYG3wqContent-Disposition: form-data;name="QueryResult"Content-Type: application/JSON;charset=utf-8-Context: efb3d3ce-ef50-4e83-8c31-063c3f5208aa{
    "status_code": 0,
    "result_type": "DRAGON_NLU_ASR_CMD",
    "NMAS_PRFX_SESSION_ID": "f786f0be-d547-4fca-8d72-96429a30c9db",
    "NMAS_PRFX_TRANSACTION_ID": "1",
    "audio_transfer_info": {
        "packages": [{
            "time": "20151221085512579",
            "bytes": 1633
        },
        {
            "time": "20151221085512598",
            "bytes": 3969
        }],
        "nss_server": "10.56.11.186:4503",
        "end_time": "20151221085512596",
        "audio_id": 1,
        "start_time": "20151221085512303"
    },
    "cadence_regulatable_result": "completeRecognition",
    "appserver_results": {
        "status": "success",
        "final_response": 0,
        "payload": {
            "actions": [{
                "speaker": "user",
                "type": "conversation",
                "nbest_text": {
                    "confidences": [478,
                    0,
                    0],
                    "words": [[{
                        "stime": 0,
                        "etime": 1710,
                        "word": "ConnectedDrive\\*no-space-before",
                        "confidence": "0.241"
                    }],
                    [{
                        "stime": 0,
                        "etime": 1020,
                        "word": "Connected\\*no-space-before",
                        "confidence": "0.0"
                    },
                    {
                        "stime": 1020,
                        "etime": 1710,
                        "word": "drive",
                        "confidence": "0.0"
                    }],
                    [{
                        "stime": 0,
                        "etime": 900,
                        "word": "Connect\\*no-space-before",
                        "confidence": "0.0"
                    },
                    {
                        "stime": 900,
                        "etime": 980,
                        "word": "to",
                        "confidence": "0.0"
                    },
                    {
                        "stime": 980,
                        "etime": 1710,
                        "word": "drive",
                        "confidence": "0.0"
                    }]],
                    "transcriptions"= ["ConnectedDrive",
                    "Connected drive",
                    "Connect to drive"]
                }
            }]
        }
    },
    "final_response": 0,
    "prompt": "",
    "result_format": "appserver_post_results"
}-Disposition: form-data;name="QueryResult"Content-Type: application/JSON;charset=utf-8-Context: efb3d3ce-ef50-4e83-8c31-063c3f5208aa{
    "status_code": 0,
    "result_type": "DRAGON_NLU_ASR_CMD",
    "NMAS_PRFX_SESSION_ID": "f786f0be-d547-4fca-8d72-96429a30c9db",
    "NMAS_PRFX_TRANSACTION_ID": "1",
    "audio_transfer_info": {
        "packages": [{
            "time": "20151221085512579",
            "bytes": 1633
        },
        {
            "time": "20151221085512598",
            "bytes": 3969
        }],
        "nss_server": "10.56.11.186:4503",
        "end_time": "20151221085512596",
        "audio_id": 1,
        "start_time": "20151221085512303"
    },
    "cadence_regulatable_result": "completeRecognition",
    "appserver_results": {
        "status": "success",
        "final_response": 1,
        "payload": {
            "diagnostic_info": {
                "adk_dialog_manager_status": "undefined",
                "nlu_version": "[NLU_PROJECT:NVCCP-eng-USA];[Datapack:Version: nlps-eng-USA-NVCCP-6.1.100.12-2-GMT20151130160932];[VL-Models:Version: vlmodels-NVCCP-eng-USA-6.1.100.12-2-GMT20151130160335]",
                "nlps_host": "mt-dmz-nlps002..com:8636",
                "nlps_ip": "10.56.10.51",
                "application": "AUDI_2017",
                "nlu_component_flow": "[Input:VoiceJSON] [FieldID|auto_main] [NLUlib|C-eckart-r$Rev$.f20151118.1250] [build|G-r72490M.f20151130.1055] [vlmodel|Version: vlmodels-NVCCP-eng-USA-6.1.100.12-2-GMT20151130160335] [Flow|+VlingoTokenized]",
                "third_party_delay": "0",
                "nmaid": "AUDI_SDS_2017_EXT_20151203",
                "nlps_profile": "AUDI_2017",
                "fieldId": "auto_main",
                "nlps_profile_package_version": "r159218",
                "nlu_annotator": "com.NVCCP.eng-GBR.ncs51.VlingoNLU-client-qNVCCP_NCS51",
                "ext_map_time": "2",
                "nlu_use_literal_annotator": "0",
                "int_map_time": "2",
                "nlps_nlu_type": "nlu_project",
                "nlu_language": "eng-GBR",
                "timing": {
                    "finalRespSentDelay": "188",
                    "intermediateRespSentDelay": "648"
                },
                "nlps_profile_package": "AUDI_2017"
            },
            "actions": [{
                "Input": {
                    "Interpretations": ["ConnectedDrive"],
                    "Type": "asr"
                },
                "Instances": [{
                    "nlu_classification": {
                        "Domain": "UDE",
                        "Intention": "Unspecified"
                    },
                    "nlu_interpretation_index": 1,
                    "nlu_slot_details": {
                        "Name": {
                            "literal": "ConnectedDrive"
                        },
                        "Search-phrase": {
                            "literal": "connecteddrive"
                        }
                    },
                    "interpretation_confidence": 4549
                }],
                "type": "nlu_results",
                "api_version": "1.0"
            }],
            "nlps_version": "nlps(z):6.1.100.12.2-B359;Version: nlps-base-Zeppelin-6.1.100-B124-GMT20151130193521;"
        }
    },
    "final_response": 1,
    "prompt": "",
    "result_format": "appserver_post_results"
}----_NMSP_vutc5w1XobDdefsYG3wq--

我正在阅读上述特定路径中的#!/usr/bin/env python import os import sys import time import webbrowser from io import BytesIO import uuid import httplib import StringIO import re import difflib import mmap import json directory =os.path.join("C:\Users\Desktop\Working\pcm-audio\English") for subdir, dirs, files in os.walk(directory): for file in files: if file.endswith(".txt"): content=json.load(file) if "status_code" in content: if content["status_code"]==0: print("valid") 文件。稍后我只检查.txt文件中的status_code

如果是0,那么我打印为有效,否则无效。后来我在.txt文件中找到转录和解释变量(我在开头展示了它包含的内容),它有一个值列表。

比较这些值,我比较了它,但我没有得到输出。我在这里使用RegEx犯了一个错误:.txt

if line.find("transcriptions") == ("Interpretations"):工作正常。但不是status_codetranscriptions

有人可以告诉我这里的错误是什么吗?

1 个答案:

答案 0 :(得分:0)

如果没有关于find实现的详细信息,那么难以回答。

我会提出一种完全不同的方法。您正在阅读的输入看起来像有效的JSON。为什么不用pythons json模块加载它。这将为您提供一个非常好的界面的python dict。

import json
info=json.load("filename.txt")
if "status" in info:
  print(info["status"])

JSON完全支持数组。您可以非常轻松地添加验证

if "actions" in info:
  value=info["actions"]
  if not isinstance(value, list):
    raise TypeException("expecting a list of actions")

我会避免使用正则表达式。现在你正在使用的正则表达式很容易阅读,但如果你的输入解析变得更复杂,这肯定会改变。正则表达式适用于验证,但我不会尝试用它们解析JSON。

注意json.loadsjson.load之间的区别。 Loads将尝试解析一个字符串,load将读取一个文件。

修改 我已经阅读了find。它似乎返回一个布尔值。你不应该将它与字符串进行比较。在python 3中,这总是错误的。这可能是您代码中的问题。

<强> EDIT2: 阅读文件列表:

filenames=["a.txt","b.txt","c.json","d.asdadf"] 
for filename in filenames:   
  content = json.load(filename)   
  if "status" in content:
    print(filename+" contains a status entry")
    status_entry=content["status"]
    print("it is: "+str(status_entry))   
  else:
    print(filename+" does not contain a status entry")

根据您的设置,这可能看起来像这样,但我还没有测试过:

directory =os.path.join("C:\Users\hemanth_venkatappa\Desktop\Working\pcm-audio\English")
for subdir, dirs, files in os.walk(directory): 
    for file in files:
        if file.endswith(".txt"): 
            content=json.load(file)
            if "status_code" in content:
              if content["status_code"]==0:
                print("valid")

您可以使用glob来获取文件名: https://docs.python.org/2/library/glob.html

import glob
glob.glob("path_to_folder/*.txt")

将返回文件名列表,例如

["path_to_folder/a.txt", "path_to_folder/asdief.txt"]

您可以在上面的代码中使用此列表。 请注意提供文件夹的正确路径。 Python有一个当前的工作目录。路径需要相对于此目录。

查看os.getcwd()以获取当前工作目录,并查看os.chdir()以更改它。

修改

该文件是某些Web查询的结果。它说

  

内容类型:application / json

但当然json解析器将无法读取该文件。你没有包含程序的输出,但我认为json.load失败了。错误方法应该类似&#34;文件不包含有效的json&#34; 。那是因为你有(http?)的标题 - 包含在文件中的响应。他们需要被删除。 你可以手动完成,你可以使用python,也许使用正则表达式。但最好的方法是不首先存储标题。你在哪里生成文件?我想你应该先调整一下这段代码。

老实说,我不认为你真的在努力解决这个问题。您只是粘贴了我的代码而没有反映您正在做的事情。阅读JSON,使用调试器并查看代码的每一行,考虑错误消息。